我是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);
?>
更新:谢谢大家,代码起作用了,确实插入了表格,但没有显示“ Row insert”:结果,我忘了从中取出分号 if 条件语句中的'execute()'。
答案 0 :(得分:6)
这里有一个准备好的声明的示例:
$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();