mysqli_real_escape_string似乎不起作用

Emo*_*ons 0 php mysql mariadb

我是PHP的新手.我试图将变量的值插入MariaDB表,并尝试使用mysqli_real_escape_string来逃避'$ value'.我从这里得到了这个想法.它向表中插入一个空字符串(我确实添加了一个到数据库的连接链接).

所以,我从PHP手册中复制并粘贴了以下代码,它仍然无法正常工作.我得到的输出只是一个错误代码:错误: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);
?>
Run Code Online (Sandbox Code Playgroud)

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

<?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);
?>
Run Code Online (Sandbox Code Playgroud)

更新:感谢球员,代码的工作,它没有插入"插入行"并没有露面的表,但:原来,我忘了取出从分号"的execute()",如果条件语句.

Pil*_*lan 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();
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请查看:准备,绑定

  • 很好的例子,但如果它适应原始问题的要求总是最好的. (2认同)