gpt4 book ai didi

php - mysqli_real_escape_string 似乎不起作用

转载 作者:行者123 更新时间:2023-12-01 00:17:38 27 4
gpt4 key购买 nike

我是 PHP 新手。我试图将一个变量的值插入到 MariaDB 表中,并试图使用 mysqli_real_escape_string 转义“$value”。我的想法来自 here .它向表中插入了一个空字符串(我确实添加了一个到数据库的连接链接)。

因此,我从 PHP Manual 复制并粘贴了以下代码,还是不行。我得到的输出只是一个错误代码:错误:42000。我错过了什么?

我正在使用 Virtualbox,操作系统:CentOS7

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City");

$city = "'s Hertogenbosch";

/* this query will fail, cause we didn't escape $city */
if (!mysqli_query($link, "INSERT into myCity (Name) VALUES ('$city')")) {
printf("Error: %s\n", mysqli_sqlstate($link));
}

$city = mysqli_real_escape_string($link, $city);

/* this query with escaped $city will work */
if (mysqli_query($link, "INSERT into myCity (Name) VALUES ('$city')")) {
printf("%d Row inserted.\n", mysqli_affected_rows($link));
}

mysqli_close($link);
?>

更新:感谢您的及时回复!我尝试了@Pilan 的代码,但无法插入一行。我在名为“城市”的数据库中创建了一个表。我检查了代码中是否有数据库连接,它确实返回了“已连接”。这是更新后的代码:

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

else {

echo "Connected";

$city = "'s Hertogenbosch";

// Connect to db, returns mysqli-connection
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

// Prepare, "?" for placeholders, returns mysqli-statement
$stmt = $mysqli->prepare("INSERT INTO City (Name) VALUES (?)");

// Bin param to statement, with type "s" for string
$stmt->bind_param("s", $city);

//Execute
/* this query with escaped $city will work */
if ($stmt->execute()) {
printf("%d Row inserted.\n", mysqli_affected_rows($link));
}

}
mysqli_close($link);
?>

更新:谢谢大家,代码有效,它确实插入到表中但“插入的行”没有显示:原来,我忘了从 中取出分号'execute()'if 条件语句中。

最佳答案

这里有一个准备好的语句的例子:

$city = "'s Hertogenbosch";    

// Connect to db, returns mysqli-connection
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

// Prepare, "?" for placeholders, returns mysqli-statement
$stmt = $mysqli->prepare("INSERT INTO myCity (Name) VALUES (?)");

// Bin param to statement, with type "s" for string
$stmt->bind_param("s", $city);

// Well execute :D
$stmt->execute();

详情请看这里:prepare , bind

关于php - mysqli_real_escape_string 似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51109781/

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