Using PDO (for any supported database driver):
$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name'); $stmt->execute([ 'name' => $name ]); foreach ($stmt as $row) { // Do something with $row }$stmt = $pdo->prepare('SELECT * FROM users WHERE name = :name'); $stmt->execute([ 'name' => $name ]); foreach ($stmt as $row) { // Do something with $row }Using MySQLi (for MySQL):
Since PHP 8.2+ we can make use ofexecute_query()which prepares, binds parameters, and executes SQL statement in one method:$result = $db->execute_query('SELECT * FROM employeesusers WHERE name = ?', [$name]); while ($row = $result->fetch_assoc()) { // Do something with $row }Up to PHP8.1:
$stmt = $db->prepare('SELECT * FROM employees WHERE name = ?'); $stmt->bind_param('s', $name); // 's' specifies the variable type => 'string' $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { // Do something with $row }
$dbConnection$dsn = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8mb4'1;charset=utf8mb4';
$dbConnection = new PDO($dsn, 'user', 'password');
$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // error reporting
$dbConnection = new mysqli('127.0.0.1', 'username', 'password', 'test');
$dbConnection->set_charset('utf8mb4'); // charset
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // error reporting
$dbConnection = new mysqli('127.0.0.1', 'username', 'password', 'test');
$dbConnection->set_charset('utf8mb4'); // charset
$preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)');
$preparedStatement->execute([ 'column' => $unsafeValue ]);
$stmt = $db->prepare('INSERT INTO table (column) VALUES (:column)');
$stmt->execute(['column' => $value]);