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.

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

报告相同问题?

悬赏问题

  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题