Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is a right safe MySQLi query? [duplicate]

Tags:

php

mysql

mysqli

Which of this is right and really safe?
Using prepared statements:

$stmt= $db->prepare("INSERT INTO books (title) VALUES (?)");
$booktitle=$_POST['booktitle'];
$stmt->bind_param('s', $booktitle);   
$stmt->execute();

Or using escape function :

$unsafe_variable = $login;
$safe_variable = mysqli_real_escape_string($unsafe_variable);
$stm=mysqli_query($db,"SELECT post_amount FROM users WHERE login='" . $safe_variable . "'");
$stmone=mysqli_fetch_assoc($stm);
$stmtwo=implode($stmone);
echo($stmtwo);

Please, help to deal with it.


1 Answers

The first option is way, way better. I can't stress this enough. Not only does it ensure you always take care of things automatically, but it also gives you cleaner code. If you don't use prepared statements, all it takes is one miss in your sanitation and you're wide open for attacks. Hell, prepared statements are half the reason mysqli was introduced in the first place.

like image 150
Joel Hinz Avatar answered Jan 20 '26 19:01

Joel Hinz