简体   繁体   中英

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?

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

use:

$userPass = mysqli_real_escape_string($mysqli,$_POST["password"]);

This block the '' or '=' thing thing :) where $mysqli is your connection string ofc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM