Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameterized queries in PHP with MySQL connection

I've read about SQL injection so I tried it with my site and of course it worked.. I know that the solution is parameterized queries and I also know that there are a lot of examples out there but none of them mentions the part where we're connecting to the database. So here's a part of my login page's PHP code:

$userName = $_POST["username"];
$userPass = $_POST["password"];

$query = "SELECT * FROM users WHERE username = '$userName' AND password = '$userPass'";

$result = mysqli_query($dbc, $query); //$dbc is for MySQL connection: $dbc = @mysqli_connect($dbhost, $dbuser, $dbpass, $db)

$row = mysqli_fetch_array($result);

if(!$row){
    echo "No existing user or wrong password.";
}

I've been looking for the solution for a long time but I just could not figure out how I could get it work in a parameterized way. Could you please help me how I should complete my code to prevent SQL injection?

like image 475
Márk Végh Avatar asked Apr 01 '16 22:04

Márk Végh


1 Answers

Here you go

$stmt = mysqli_prepare($dbc, "SELECT * FROM users WHERE username = ? AND password = ?");
mysqli_stmt_bind_param($stmt, "s", $userName);
mysqli_stmt_bind_param($stmt, "s", $userPass);
mysqli_stmt_execute($stmt);
$row = mysqli_stmt_fetch($stmt);

Documentation

As side note i would reccomend to encrypt your password or better use hash for security, it's not good to store password as plain text

like image 137
Fabio Avatar answered Nov 04 '22 22:11

Fabio