mysqli_real_escape_string not working correctly

蹲街弑〆低调 提交于 2019-12-11 06:44:53

问题


I am trying to use both mysqli_real_escape_string and trim together before making a MySQL INSERT query. My code is as follows:

<?php
$fname = mysqli_real_escape_string($dbc, trim($_POST['fname']));
$sname = mysqli_real_escape_string($dbc, trim($_POST['sname']));
$occ = mysqli_real_escape_string($dbc, trim($_POST['occ']));
$twitter = mysqli_real_escape_string($dbc, trim($_POST['twitter']));
$email = mysqli_real_escape_string($dbc, trim($_POST['email']));
$skype = mysqli_real_escape_string($dbc, trim($_POST['skype']));
$topic1 = mysqli_real_escape_string($dbc, trim($_POST['topic1']));
$topic2 = mysqli_real_escape_string($dbc, trim($_POST['topic2']));
$topic3 = mysqli_real_escape_string($dbc, trim($_POST['topic3']));
$avoid1 = mysqli_real_escape_string($dbc, trim($_POST['avoid1']));
$avoid2 = mysqli_real_escape_string($dbc, trim($_POST['avoid2']));
$avoid3 = mysqli_real_escape_string($dbc, trim($_POST['avoid3']));
$cr = mysqli_real_escape_string($dbc, trim($_POST['cr']));

if ((!empty($fname)) && (!empty($sname)) && (!empty($email)) && (!empty($topic1))) {
    $dbc = mysqli_connect('host', 'user', 'password', 'database') or die('Error connecting to MySQL server');
    $query = "INSERT INTO initial_details (fname, sname, occ, twitter, email, skype, topic1, topic2, topic3, avoid1, avoid2, avoid3, cr) VALUES ('$fname', '$sname', '$occ', '$twitter', '$email', '$skype', '$topic1', '$topic2', '$topic3', '$avoid1', '$avoid2', '$avoid3', '$cr')";
    $result = mysqli_query($dbc, $query);
    if (!$result) {
        mysqli_close($dbc);
        echo 'Duplicate';
    } else {
        mysqli_close($dbc);
        echo 'Success - entry added';
    }
} else {
    echo 'Error';
}   
?>

Using the code as above I get the 'Error' message, however if I remove mysqli_real_escape_string() and just use trim I am able to insert my entry successfully.

Why am I not able to use mysqli_real_escape_string() in this scenario?


回答1:


$dbc = mysqli_connect must precede all the mysqli_real_escape_string calls to make it work. This is because you need an active mysqli connection to use that function.




回答2:


You have to connect to your database first.
Turning on error reporting also helps.




回答3:


$dbc = mysqli_connect must precede all the mysqli_real_escape_string calls to make it work. This is because you need an active mysqli connection to use that function. What does this one means. Need it more detailed?



来源:https://stackoverflow.com/questions/9055974/mysqli-real-escape-string-not-working-correctly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!