我是php的新手。我试图将变量的值插入mariadb表,并试图使用mysqli\u real\u escape\u string来转义“$value”。我是从这里想到的。它向表中插入了一个空字符串(我确实向数据库添加了一个连接链接)。
所以,我从php手册中复制并粘贴了下面的代码,它仍然不起作用。我得到的输出仅仅是一个错误代码:error:42000。我错过了什么?
我使用的是virtualbox,os: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的代码,但没能插入一行。我在数据库中创建了一个名为“city”的表。我检查了代码中是否有数据库连接,它确实返回“connected”。以下是更新的代码:
<?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);
?>
更新:谢谢大家,代码成功了,它确实插入到了表中,但是“row inserted”没有出现:结果是,我忘了从if条件语句中的“execute()”中去掉分号。
1条答案
按热度按时间mv1qrgav1#
下面是一个准备好的语句示例:
详情请看这里:准备,绑定