Top Mistakes of Beginner PHP Developers — Part 4: Working with Data

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Топ ошибок начинающих PHP разработчиков — часть 4: Работа с данными



Продолжаем серию статей для тех, кто изучает PHP и хочет писать более качественный код. В этой части мы разберем три критических ошибки, связанных с обработкой пользовательских данных, кешированием и строгой типизацией. Если вы находитесь на этапе обучения PHP, эти примеры помогут вам избежать типичных проблем в реальных проектах.



1. Trusting data from superglobal arrays



One of the most common mistakes for beginner PHP developers is using data from $_GET, $_POST or $_REQUEST without validation and filtering. This is a direct path to XSS attacks and SQL injections.



Wrong approach

<?php// Dangerous! User can send a script$name = $_POST['username'];echo "Hello, $name!";?>


Correct approach

<?php// Use filtering and escaping$name = htmlspecialchars(strip_tags(trim($_POST['username'] ?? '')), ENT_QUOTES, 'UTF-8');echo "Hello, " . $name . "!";?>


What to do? Always process incoming data. For working with databases, use prepared statements (PDO or MySQLi), and for output — htmlspecialchars(). This is the foundation of security in PHP programming.



2. Lack of caching for heavy queries



Many beginners execute the same SQL query or complex calculation on every page refresh. This kills performance, especially when there are many queries.



Example of the problem

<?php// Request data from the database every time$users = $db->query("SELECT * FROM users WHERE active = 1")->fetchAll();foreach ($users as $user) {    echo $user['name'];}?>


Solution with caching

<?php// Use simple file caching$cacheFile = 'cache/users_active.cache';$cacheTime = 300; // 5 minutes

if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < $cacheTime) { $users = unserialize(file_get_contents($cacheFile));} else { $users = $db->query("SELECT * FROM users WHERE active = 1")->fetchAll(); file_put_contents($cacheFile, serialize($users));}

foreach ($users as $user) { echo $user['name'];}?>


For more complex projects, use Memcached or Redis. This will speed up learning PHP in terms of understanding the architecture of high-load applications.



3. Ignoring strict typing



PHP is a dynamically typed language, but since version 7.0 it has become possible to enable strict mode. Beginners often forget about this, which leads to unexpected errors.



Typical situation

<?phpfunction calculateSum($a, $b) {    return $a + $b;}

echo calculateSum(10, '5'); // Result: 15 (string converted to number)?>


Fix

<?phpdeclare(strict_types=1); // Enable strict mode

function calculateSum(int $a, int $b): int { return $a + $b;}

// echo calculateSum(10, '5'); // Fatal error: Uncaught TypeErrorecho calculateSum(10, 5); // 15?>


Strict typing helps catch errors at the development stage, not in production. We recommend that everyone PHP for beginners immediately get used to specifying argument and return value types.



Bonus: working with sessions without checking



Another common mistake is writing to a session without checking if the key exists. This can cause warnings.



<?phpsession_start();

// Error: if the key does not exist, we get a warning$_SESSION['counter'] = $_SESSION['counter'] + 1;

// Correct$_SESSION['counter'] = ($_SESSION['counter'] ?? 0) + 1;?>

Blogs

Book Recommendations