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.

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度