为什么双引号在mysql查询中消失?

Jos*_*sen 2 php mysql

我有这个代码:

<?php
   $conn = mysqli_connect("localhost", $db['username'], $db['password'], "the_table");

   // Check connection
   if (!$conn) {
       die("Connection failed: " . mysqli_connect_error());
   }

   $sql = "SELECT * FROM xlsws_images";

   if(!$result = $conn->query($sql)){
       die('There was an error running the query [' . $db->error . ']');
   }

   while($row = $result->fetch_assoc()){
       $path = $row['image_path'];
       echo $path;
   }
?>
Run Code Online (Sandbox Code Playgroud)

它按预期工作,直到它到达一个带有image_path双引号的行,例如product/1/1”-wood-wheel-casters-set-of-4.png.在这种情况下,它返回没有双引号的路径,就像这样product/1/1-wood-wheel-casters-set-of-4.png.

是什么让这些报价消失,我怎么能避免这种情况?

Fun*_*ner 6

"......有双引号,如产品/ 1/1""

这是一个卷曲(智能)引用,应该改为".(如果你在问题中向我们展示的是你数据库中实际的引用类型).

这就是为什么它失败了你从一开始就被引入你的数据库.

你可以使用REPLACE

在你的表中更改它们.(甚至删除它们).

理想情况下,你应该在它到达db之前解决这个问题.


编辑:

在测试期间,以下是echo'd product/1/1”-wood-wheel-casters-set-of-4.png

$result = $connection->query("SELECT * FROM table");

while($row = $result->fetch_object()){

   echo $row->path_column;

}
Run Code Online (Sandbox Code Playgroud)

因此,很难说是导致代码失败的原因.

您可以尝试的一些事情是:

$path = mysqli_real_escape_string($conn, $row['image_path']);
Run Code Online (Sandbox Code Playgroud)

$path = htmlentities(stripslashes($row['image_path']));
Run Code Online (Sandbox Code Playgroud)

使用示例 str_replace():

$str = "product/1/1”-wood-wheel-casters-set-of-4.png";

echo $newstring = str_replace("”", "", $str);
Run Code Online (Sandbox Code Playgroud)

哪个产生:

product/1/1-wood-wheel-casters-set-of-4.png

  • 如果您希望在文件上传方面走这条路线.

请参阅堆栈上的以下问答以在上传文件期间替换字符(重命名):

旁注:它意味着用下划线替换空格,但您可以基于相同的逻辑.


还有一些可能有用的例子.

这摆脱了引用:

$result = $conn->query("SELECT * FROM table");

while($row = $result->fetch_object()){

    $new = $row->path_column;
    $newstring = str_replace("”", "", $new);

}

echo $newstring;
Run Code Online (Sandbox Code Playgroud)

并将新更改的卷曲报价转换为常规报价:

$result = $conn->query("SELECT * FROM table");

while($row = $result->fetch_object()){

    $new = $row->path_column;
    $newstring = str_replace("”", "\"", $new);

}

echo $newstring;
Run Code Online (Sandbox Code Playgroud)

哪一个产生了 product/1/1"-wood-wheel-casters-set-of-4.png

  • 注意"而不是智能引用.

编辑:

事实证明,这是在设置连接之前传递UTF-8的问题.

OP:"太棒了!$conn->set_charset('utf8mb4');工作.这就是我需要添加到上面的代码中的所有内容.现在无缝地工作.谢谢! - Joshua Goossen".

根据我对OP的评论:

"你也可以尝试在查询之前设置为UTF-8作为你的连接.看看堆栈UTF-8上的这个Q&A 一直到那里有几个答案.连接的东西就是$connection->set_charset('utf8mb4');一个例子,并在之前使用你打开数据库连接."