$ mysqli-> real_escape_string()和addslashesh()无法正常工作

时间:2015-10-08 10:32:26

标签: php mysql

我已在我的服务器上测试了$mysqli->real_escape_string()addslashesh(),但他们都没有完成自己的工作。

当我在表格的名称字段中输入“'What what”yolo“是什么意思?'”时,它在数据库中存储了“'什么”yolo“是什么意思?'”。 问题出在哪里?

 <?php
    require_once("../private/initialize.php");
    header("Content-Type: text/plain"); 




    if(request_is_post() && request_is_same_domain()){

    if(isset($_POST["name"])  && !empty($_POST["name"]) && isset($_POST["lastname"]) && !empty($_POST["lastname"]) && isset($_POST["birthday"]) && !empty($_POST["birthday"])&&  isset($_POST["email"]) && !empty($_POST["email"]) && isset( $_POST["password"]) && !empty($_POST["password"]) && isset($_POST["confirmPassword"]) && !empty($_POST["confirmPassword"]) ){

        $now=date("Y-m-d");
        $time = time()+5460;
            $name            = $_POST["name"];
            $lastname        =$conn->real_escape_string($_POST["lastname"]);
            $birthday        =$conn->real_escape_string($_POST["birthday"]);
            $email           =$conn->real_escape_string(strtolower($_POST["email"]));
            $password        =$conn->real_escape_string($_POST["password"]);
            $hashed_password = password_hash($password, PASSWORD_BCRYPT);   
            $time = time()+5460;


                $result=$conn->prepare("INSERT INTO students (student_name,student_family,student_birthday,student_email,student_password,register_date,register_time)
VALUES (?,?,?,?,?,?,?)"); 
 $result->bind_param("sssssss",$name, $lastname, $birthday, $email,$hashed_password,$now,$time);
        if($result->execute()){
    $result->close();

    echo "yes";
    }
        else {$result->close();
    echo "Error: " . $sql . "<br>" . $conn->error;
}




    }else


{  echo "no";}  

        $conn->close();     


} else{ echo "no";

      $conn->close();   }

    ?>

1 个答案:

答案 0 :(得分:-1)

MySQLi预编译语句是出于多种目的而设计的。我最喜欢的是你在将数据插入数据库之前不需要调用real_escape_string()。它会自己做。

如何做MySQLi预备语句:

<?PHP
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// prepare and bind
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);

// set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "john@example.com";
$stmt->execute();
$stmt->close();
$conn->close();
?>