简体   繁体   中英

mysqli_real_escape_string not working correctly

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?

$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.

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

$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?

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