【问题标题】:PHP MySQLI prepared insert to handle quotes and double quotesPHP MySQLI准备插入来处理引号和双引号
【发布时间】:2014-09-19 04:10:57
【问题描述】:

我有一个准备好的 mysqli 插入语句,但是当我尝试用引号或双引号插入数据时,我收到了这个错误:Prepare failed: (1064) You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Ask me in six months.' We don’t have six months to wait," he said. "I have a p' at line 1

当我在尝试插入的文本周围使用mysqli_real_escape_string 时,它会作为空数据插入到我的数据库中。

有没有更好的方法来处理单引号或双引号?还是我的代码有问题?

$connection = new mysqli("localhost", "username", "password", "database");

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

if (!($stmt = $connection->prepare("INSERT INTO `in-the-press` (title, `date`, preview, description, image, detailImage, showDetailImage) VALUES ('" . $title . "', '" . $date . "', '" . $preview . "', '" . $description . "','" . $image . "', '" . $detailImage . "', " . $showDetailedImage . ")"))) {
                        echo "Prepare failed: (" . $connection->errno . ") " . $connection->error;
                }else{

                        $stmt->execute();
                        echo 'Press has been added <br>';
                }

我尝试过使用mysqli_real_escape_string($title), mysqli_real_escape_string($preview) &amp; mysqli_real_escape_string($description),但就像我说的它会将其作为空字符串插入数据库:(

【问题讨论】:

  • 既然你使用的是prepare()/execute(),你也应该使用be using bind_param()。这样做完全避免了这个引用问题,同时也确保了 SQL 注入的安全性。
  • 我有点明白,但我不明白这个:$stmt-&gt;bind_param('sssd', $code, $language, $official, $percent);sssd 是什么意思?

标签: php mysqli


【解决方案1】:

正如迈克尔在他的 comment 中所说的那样


由于您将mysqliprepare()execute() 一起使用,因此最好使用bind_param()

$stmt = $mysqli->prepare("INSERT INTO `in-the-press` (title, `date`, preview, description, image, detailImage, showDetailImage) VALUES (?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param('sssssss', $title, $date, $preview, $description, $image, $detailImage, $showDetailedImage);


/* execute prepared statement */
$stmt->execute();

printf("%d Row inserted.\n", $stmt->affected_rows);

/* close statement and connection */
$stmt->close();

以上只是一个例子,我不知道你的数据库架构/结构是什么样的

细分:

  • s 表示字符串。
  • d 表示双倍。

您可以在上面的bind_param 链接中阅读有关类型(isdb)的更多信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-16
    • 2019-07-20
    • 2023-03-25
    • 1970-01-01
    • 2011-06-02
    • 2013-03-24
    • 1970-01-01
    相关资源
    最近更新 更多