mysql real escape string solve sql injection definitely [duplicate]

我的未来我决定 提交于 2019-12-12 06:27:06

问题


I want to know if I add mysql_real_escape_string to my variables that's enough to solve sql injection

$get_id = "select * from `book` where id='".$mysqli->real_escape_string($id)."' limit 1";

回答1:


No, it isn't. Use prepared statements.

You would have to do something like this:

// Your connection settings
$connData = ["localhost", "user", "pass", "database"];

$conn = new mysqli($connData[0], $connData[1], $connData[2], $connData[3]);
$conn->set_charset("utf8");

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Here we explain MySQL which will be the query
$stmt = $conn->prepare("select * from book where id=? limit 1");

// Here we tell PHP which variable hash de "?" value. Also you tell PHP that $id has an integer ("i")
$stmt->bind_param("i", $id);

// Here we bind the columns of the query to PHP variables
$stmt->bind_result($column1, $column2, ...); // <--- Whichever columns you have

// Here we execute the query and store the result
$stmt->execute();
$stmt->store_result();

// Here we store the results of each row in our PHP variables ($column1, column2, ...)
while($stmt->fetch()){
    // Now we can do whatever we want (store in array, echo, etc)
    echo "<p>$column1 - $column2 - ...</p>";
}

$stmt->close();
$conn->close();


来源:https://stackoverflow.com/questions/37218691/mysql-real-escape-string-solve-sql-injection-definitely

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