Parameterized queries in PHP with MySQL connection

戏子无情 提交于 2019-12-10 15:27:27

问题


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?


回答1:


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




回答2:


use:

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

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



来源:https://stackoverflow.com/questions/36366754/parameterized-queries-in-php-with-mysql-connection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!