PHP MySQLI准备插入来处理引号和双引号

时间:2014-07-28 01:23:50

标签: php mysqli

我有一个准备好的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) & mysqli_real_escape_string($description),但就像我说它会将其作为空字符串插入数据库:(

1 个答案:

答案 0 :(得分:1)

正如迈克尔在comment

中所说的那样

由于您mysqli使用了prepare()&amp; 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表示加倍。

您可以在上面i链接中详细了解类型(sdbbind_param)。