0

I am learning to use prepared statements to add security against SQL injections... I have written the below code and am looking for feedback on if the code is correct/secure.

$user= mysqli_real_escape_string($conn, $_GET['user']);

$sql = "SELECT user_name, about, avatar FROM users WHERE user_name = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $user); // 's' specifies type => 'string'
$stmt->execute();

$result = $stmt->get_result();
while ($users = $result->fetch_assoc()) {
// Do something with the result

$avatar   =   !empty($users['avatar']) ? $users['avatar'] : 'default.png';
$uname = $users['user_name'];
$about = $users['about'];

}

the above code works fine, but if I made a mistake or forgot to add something please let me know as I am still learning about PHP/SQL security.

MrShakila
  • 874
  • 1
  • 4
  • 19
505notfound
  • 13
  • 1
  • 5
  • create user name with quote inside (`Jeanne d'Arc`) and test your code – Iłya Bursov Oct 16 '22 at 15:58
  • 1
    Remove the first line and you're OK – Your Common Sense Oct 16 '22 at 15:59
  • `while` is also useless in your case though. while is used to get multiple rows and you need only one. A prettified version of your code would be https://phpize.online/sql/mysql57/undefined/php/php81/95f50ca9fbd56ece5d71652445490dd7/ – Your Common Sense Oct 16 '22 at 16:24
  • If you're just starting out with PHP, do yourself a favor and use [PDO](https://www.php.net/pdo). It's more powerful and easier to use than Mysqli. In my opinion, the only reason to use Mysqli is that it's a little easier if you are updating very old PHP 5.x code that used the now deprecated Mysql PHP extension. – Bill Karwin Oct 18 '22 at 17:53

0 Answers0