简体   繁体   中英

PHP and MySQL - correct way to use mysqli_real_escape_string

I was wondering if the code below is the correct way to use mysqli_real_escape_string() when storing users data in a database.

Here is the PHP & MySQL code.

if (mysqli_num_rows($dbc) == 0) {
        $mysqli = mysqli_connect("localhost", "root", "", "sitename");
        $dbc = mysqli_query($mysqli,"INSERT INTO info (user_id, url) 
                                     VALUES ('$user_id', 'mysqli_real_escape_string($url)')");
}


if ($dbc == TRUE) {
        $dbc = mysqli_query($mysqli,"UPDATE info 
                                     SET url = 'mysqli_real_escape_string($url)' 
                                     WHERE user_id = '$user_id'");

No, mysqli_real_escape_string() is not executed within your string. You need to move it out into the PHP code:

$eUrl = mysqli_real_escape_string($url);
mysqli_query($mysqli, "INSERT ... VALUES ('$eUrl')");

But I (and, I'm sure, others here) will argue that PDO and variable binding are the "correct" way to escape things in this modern world.

Almost: You need to put the function calls outside the string:

"... VALUES ('$user_id', '".mysqli_real_escape_string($url)."')");

Notice the closing " and the concatenating . before and after the function call.

And, we don't know where $user_id comes from. If it comes from the outside, that needs to be escaped, too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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