如何在脚本中使用mysqli_real_escape_string
来阻止SQL注入。我正在编写一些代码并在这里提出一些问题,我被建议使用mysqli_real_escape_string
而不是mysql_real_escape_string
,问题是我的代码在我想要保护的变量之后才建立连接。有人建议我应该使用预备语句,但经过一些搜索后http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php我感到更加困惑。现在代码如果完全按照它不应该做的那样,它将空值/行插入到我的表中,从我的阅读中可能是因为使用了mysqli_real_escaape_string
任何想法或帮助都表示赞赏,我非常沮丧和困惑,但仍在努力学习。这是代码:
<?php
//Form fields passed to variables
$manu = mysqli_real_escape_string($_POST['inputManu']);
$model = mysqli_real_escape_string($_POST['inputModel']);
$desc = mysqli_real_escape_string($_POST['inputDesc']);
//Connect to database using $conn
include ('connection.php');
//Insert record into table
$sql = "INSERT INTO gear (`id`,`manu`,`model`,`desc`)
VALUES (NULL,'$manu','$model','$desc')";
//Check for empty fields
if (isset($_POST['submit']))
{
foreach($_POST as $val)
{
if(trim($val) == '' || empty($val))
{
die('Error: ' . mysqli_error());
echo "Please complete all form fields!";
echo "<meta http-equiv='Refresh' content='3; URL=../add.php'>";
}
}
if (!mysqli_query($conn,$sql))
{
die('Error: ' . mysqli_error($conn));
}
else
{
//echo "1 record added";
echo "Success, You added the ".$manu." ".$model."";
echo "<meta http-equiv='Refresh' content='3; URL=../index.php'>";
}
}
else
{
echo "some error";
}
mysqli_close($conn);
?>
答案 0 :(得分:5)
<?php
//Connect to database using $conn
include ('connection.php');
//Form fields passed to variables
$manu = mysqli_real_escape_string($conn, $_POST['inputManu']);
$model = mysqli_real_escape_string($conn, $_POST['inputModel']);
$desc = mysqli_real_escape_string($conn, $_POST['inputDesc']);
答案 1 :(得分:0)
希望下面的代码可以帮到你。
<?php
//Connect to database using $conn
/*in connection.php
$link = mysqli_connect("localhost", "root", "", "test");
*/
include ('connection.php');
//Check for empty fields
if (isset($_POST['submit']))
{
//Form fields passed to variables
$manu = mysqli_real_escape_string($link,$_POST['inputManu']);
$model = mysqli_real_escape_string($link,$_POST['inputModel']);
$desc = mysqli_real_escape_string($link,$_POST['inputDesc']);
if($manu!='' && $model!="" && $desc!="")
{
//Insert record into table
$sql = "INSERT INTO gear (`id`,`manu`,`model`,`desc`)
VALUES (NULL,'$manu','$model','$desc')";
$r=mysqli_query($link,$sql) ;
//echo "1 record added";
if($r)
{
echo "Success, You added the ".$manu." ".$model."";
// echo "<meta http-equiv='Refresh' content='3; URL=../index.php'>";
}
}
else
{
echo "Please complete all form fields!";
}
}
?>