使用MYSQLI插入时出错

时间:2016-09-13 03:06:49

标签: php html

我是这个PHP的新手,请帮助我,我无法在表中插入值。 但是,如果我直接将值赋给insert命令代替变量,那就可以了。

<?php
include ("db.php"); 
$msg = "";
if(isset($_POST["submit"]))
{
    $name = $_POST["name"];
    $email = $_POST["email"];
    $password = $_POST["password"];
    $name = mysqli_real_escape_string($db, $name);
    $email = mysqli_real_escape_string($db, $email);
    $password = mysqli_real_escape_string($db, $password);
    $password = md5($password);
    $sql="SELECT email FROM users2 WHERE email='$email'";
    $result=mysqli_query($db,$sql);
    $row=mysqli_fetch_array($result,MYSQLI_ASSOC);
    if(mysqli_num_rows($result) == 1)
    {
        $msg = "Sorry...This email already exist...";
    }
    else
    {
        $query = mysqli_query($db, "INSERT INTO users2 (name, email, password)VALUES ('$name', '$email', '$password')");
        if($query)
        {
            $msg = "Thank You! you are now registered.";
        }
    }
}
?>

2 个答案:

答案 0 :(得分:0)

$sql = "INSERT INTO users2 (name, email, password) VALUES (?,?,?)";
            if (!$stmt = $db->prepare($sql)) {
            die($db->error);
            }
            $stmt->bind_param("sss", $name, $email, $password);
            if (!$stmt->execute()) {
            die($stmt->error);
            }

我不知道上面问题中的问题是什么,但是 我使用上面的查询而不是我使用的问题和Boom它是成功的。 如果你们其中任何一个人知道问题中的问题,请告诉我。

答案 1 :(得分:-1)

你必须在insert的字符串中连接变量而不仅仅是作为变量

$query = mysqli_query($db,"INSERT INTO users2 (name, email, password)VALUES ('".$name."', '".$email."', '".$password."')")

$query = mysqli_query($db,"INSERT INTO users2 (name, email, password)VALUES ('{$name}', '{$email}', '{$password}')")

您应该对此mysql_real_escape_string-versus-Prepared-Statements

使用prepare语句

绝不使用md5() is-md5-considered-insecure

首选password_hash()password_verify() Manuel

``