Hi friends, my name is Ricardo Sawir. Follow and subscribe if you like to get more updates on what I make:

Okay, I think that's enough 😁 I collect these tips and code snippets mostly from the awesome communities in StackOverflow. This code snippets and advice works but not limited from PHP 5 to PHP 8. I curate this myself and use it firstly for my job.

I don't claim any of these code snippets or tips written here as mine. The credits goes to the respective authors. All of these tips and code snippets are collected by me that I see as "useful" for me and I hope you find them useful, too.

If you find any errors, probably a typo from me, please let me know at my email (you can find at the bottom).

So, let's jump directly to our 1st tip!

1. Use Prepared Statements if you are working with database to prevent SQL injection

Source: https://stackoverflow.com/a/60496/9478774

$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');

$stmt->execute([ 'name' => $name ]);

foreach ($stmt as $row) {
    // Do something with $row
}

This is to set up the connection, you can copy paste this:

$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'password');

$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)');

$preparedStatement->execute([ 'column' => $unsafeValue ]);