简体   繁体   English

PHP mysqli_real_escape_string()在函数内部不起作用

[英]PHP mysqli_real_escape_string() not working inside function

I have a function that adds a log entry to my database as follows: 我有一个向数据库添加日志条目的功能,如下所示:

function doLog($conn, $category, $result, $details){
    $category = mysqli_real_escape_string($conn, $category);
    $result = mysqli_real_escape_string($conn, $result);
    $details = mysqli_real_escape_string($conn, $details);

    mysqli_query($conn, "INSERT INTO log (category, result, details) VALUES('$category', '$result', '$details')");
    return $details; //for debug
}

echo doLog2($conn, "Test", "Test", "A 'test' entry"); //echo is for debug

A 'test' entry is returned/echoed as A \\'test\\' entry , but is inserted into my database without the slashes. 一个'test'条目作为一个\\'test \\ '条目被返回/回显,但是没有斜杠插入到我的数据库中。

How can this be? 怎么会这样?

This is working correctly. 这工作正常。 The backslashes are to escape the quotes in the SQL query, so that the quote characters are inserted verbatim. 反斜杠用于转义SQL查询中的引号,以便逐字插入引号字符。 It's not supposed to also insert the escape character \\ . 不应同时插入转义字符\\

If you had applied escaping twice, you'd end up with an escaped backslash followed by an escaped quote like this: 如果您两次应用了转义,您将得到一个转义的反斜杠,然后是一个转义的引号,如下所示:

A \\\'test\\\' entry

What would be stored in the database would be: 存储在数据库中的将是:

A \'test\' entry

All this is much simpler if you use parameterized statements. 如果您使用参数化语句,那么所有这些操作都将更加简单。 You don't do any quoting or escaping. 您不做任何引用或转义。

function doLog($conn, $category, $result, $details){
    $sql = "INSERT INTO log (category, result, details) VALUES (?, ?, ?)";
    $stmt = mysqli_prepare($conn, $sql);
    mysqli_stmt_bind_param($stmt, "sss", $category, $result, $details);
    mysqli_stmt_execute($stmt);

    return $details; //for debug
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM