gpt4 book ai didi

php - mysqli_real_escape_string 不插入数据库

转载 作者:搜寻专家 更新时间:2023-10-30 22:05:51 25 4
gpt4 key购买 nike

我提出以下问题...我必须确保以下查询也接受带引号的值...我尝试使用 mysqli_real_escape_string 但它没有用..我附上我的尝试..

1° 将功能放在帖子中

        $idCantiere = $_POST["idCantiere"];
$nomeCantiere = mysqli_real_escape_string($_POST["nomeCantiere"]);
$sql = "INSERT INTO Cantiere(
idCantiere,
nomeCantiere)
VALUES(
'$idCantiere',
'$nomeCantiere')";
if (mysqli_query($mysqli, $sql))
{
echo "<script type='text/javascript'>alert('Cantiere Inserto');
</script>";
} else
{
echo "Error: " . $sql . "" . mysqli_error($mysqli);
}

2°在查询过程中放置​​函数

 $idCantiere = $_POST["idCantiere"];
$nomeCantiere = $_POST["nomeCantiere"];
$sql = "INSERT INTO Cantiere(
idCantiere,
nomeCantiere)
VALUES(
'$idCantiere',
mysqli_real_escape_string('$nomeCantiere'))";
if (mysqli_query($mysqli, $sql))
{
echo "<script type='text/javascript'>alert('Cantiere Inserto');
</script>";
} else
{
echo "Error: " . $sql . "" . mysqli_error($mysqli);
}

我该如何解决这个问题?

最佳答案

删除 mysqli_real_escape_string() 并只使用准备好的语句,这很简单并且可以防止 sql 注入(inject)。

<?php

$idCantiere = isset($_POST['idCantiere']) ? $_POST['idCantiere'] : null;
$nomeCantiere = isset($_POST['nomeCantiere']) ? $_POST['nomeCantiere'] : null;


$sql = $mysqli->prepare("INSERT INTO Cantiere (idCantiere,nomeCantiere) VALUES(?.?)");
$sql->bind_param("is",$idCantiere,$nomeCantiere);

if($sql->execute()){

//success message
}else{

//return error
}


?>

预处理语句是一种用于高效地重复执行相同(或相似)SQL语句的特性。

准备好的语句基本上是这样工作的:

准备:SQL 语句模板被创建并发送到数据库。某些值未指定,称为参数(标记为“?”)。示例:INSERT INTO MyGuests VALUES(?, ?, ?)数据库对SQL语句模板进行解析、编译、查询优化,并存储结果而不执行执行:稍后,应用程序将值绑定(bind)到参数,数据库执行该语句。应用程序可以使用不同的值多次执行该语句与直接执行 SQL 语句相比,预处理语句具有三个主要优势:

准备好的语句减少了解析时间,因为查询的准备只做了一次(尽管语句被执行了多次)绑定(bind)参数最小化服务器带宽,因为您每次只需要发送参数,而不是整个查询准备好的语句对 SQL 注入(inject)非常有用,因为稍后使用不同协议(protocol)传输的参数值不需要正确转义。如果原始语句模板不是来自外部输入,则不会发生SQL注入(inject)。

关于php - mysqli_real_escape_string 不插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54981838/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com