douangoo48863 2017-11-29 23:09
浏览 138
已采纳

为什么mysqli_real_escape_string在我的字符串中添加两个反斜杠

I am running php 5.5.9

I am POSTing the following text to a php script that will insert it into the field of a mysql table.

This is becoming quite a nuisance ' and why is that

I am using the following code to assign POSTed data to a variable (plus debugging code.)

$ITEMDESC2 = $_POST['ITEMDESC'];
$ITEMDESC = mysqli_real_escape_string($conn1, $ITEMDESC2);

error_log("ITEMDESC: $ITEMDESC  ITEMDESC2: $ITEMDESC2");

The following appears in my apache log file:

ITEMDESC: This is becoming quite a nuisance \\' and why is that
ITEMDESC2: This is becoming quite a nuisance ' and why is that

Why is $ITEMDESC being escaped with double backslashes, instead of single backslashes?

I have read that this can be caused by magic_quotes, but as I understand it, they were removed in PHP 5.4

Any insight into this would be welcome.

Edit: Adding more complete, working example as requested.

<?php 
$conn1 = new mysqli('localhost', 'USER', 'PASSWORD', 'DB') 
or die ('Cannot connect to db');

$ITEMDESC = "This is Bob's Text";
$ITEMDESC2 = mysqli_real_escape_string($conn1, $ITEMDESC);
$SQL = "insert into table (description) values ('{$ITEMDESC2}');";

echo "<br>ITEMDESC: {$ITEMDESC}";
echo "<br>ITEMDESC2: {$ITEMDESC2}";
echo "<br>SQL: {$SQL}";

error_log("ITEMDESC: {$ITEMDESC}");
error_log("ITEMDESC2: {$ITEMDESC2}");
error_log("SQL: {$SQL}");
?>

apache2 error log contains:

ITEMDESC: This is Bob's Text
ITEMDESC2: This is Bob\\'s Text
SQL: insert into table (description) values ('This is Bob\\'s Text');

browser output (on-screen):

ITEMDESC: This is Bob's Text
ITEMDESC2: This is Bob\'s Text
SQL: insert into table (description) values ('This is Bob\'s Text');

  • 写回答

1条回答 默认 最新

  • duanqiao0153 2017-11-29 23:36
    关注

    You should migrate your code to prepared statements instead. That would let you avoid this strange issue and also provide better security.

    $stmt = mysqli_prepare($link, 'INSERT INTO FooBar(description) VALUES (?)');
    mysqli_stmt_bind_param($stmt, 's', $_POST['ITEMDESC']);
    mysqli_stmt_execute($stmt);
    

    Though, I personally perfer using PDO, because it had the option to have named parameters, that make the SQL a lot more readable and the interface is PSR-2 comaptible.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮