如何保护来自输入的 SQL 查询? [英] How to secure SQL query from input?
问题描述
如何保护来自输入的 SQL 查询?
How to secure SQL query from input?
我将参数发布到 php & 中的页面然后我必须将它插入数据库但我不知道如何保护输入参数
I am posting parameter to a page in php & then I have to insert it into database but I don't know how to secure the input parameter
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO Persons (FirstName, LastName, Age)
VALUES ($_POST['FirstName'], $_POST['LastName'],$_POST['Age'])");
mysqli_close($con);
?>
推荐答案
您可以使用 mysqli
函数集通过预先转义这些字符串轻松地做到这一点.MySQL PHP 驱动程序包含安全转义字符串以插入字符串的函数 -> mysqli_real_escape_string
.
You can easily do this with the mysqli
set of functions by escaping those strings beforehand. The MySQL PHP drivers contains a function to safely escape strings for insertion into a string -> mysqli_real_escape_string
.
这会将您的查询更改为:
That would change your query to:
mysqli_query($con,"INSERT INTO Persons (FirstName, LastName, Age) VALUES ('" . mysqli_real_escape_string($_POST['FirstName']) . "', '" . mysqli_real_escape_string($_POST['LastName']) . "', '" . mysqli_real_escape_string($_POST['Age']) . "')");
这将解决您与保护 SQL 输入相关的大部分问题.
This will handle the majority of your concerns with securing input for SQL.
可选
通过使用准备好的语句,充分利用驱动程序转义其他类型和更安全的查询,您也可以使用 mysqli
如:
Take full advantage of the driver escaping for other types and safer queries by using prepared statements, which you can also do with mysqli
like:
// Prepare our query
$stmt = mysqli_prepare($con, "INSERT INTO Persons (FirstName, LastName, Age) VALUES (?, ?, ?)");
// Bind params to statement
mysqli_stmt_bind_param($stmt, "ssi", $_POST["FirstName"], $_POST["LastName"], $_POST["Age"]);
// Execute the query
mysqli_stmt_execute($stmt);
这篇关于如何保护来自输入的 SQL 查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!