数据未插入sql

时间:2019-06-10 18:53:18

标签: php html

数据未插入sql

密码不相等时,密码不起作用。但是,当密码匹配时,我的sql中没有数据被更新。 已经尝试直接从数据库将数据导入sql,并且还确认到数据库的连接已完成。

<?php

       $host= 'localhost';
       $user= 'root';
       $pass= '';
       $db= 'newusers';

       $name = $_POST['name'];
       $surname = $_POST['surname'];
       $email = $_POST['email'];
       $password = $_POST['password'];


       $con=mysqli_connect($host,$user,$pass,$db);
        if($con)
                /*echo 'Connected Successfully to newusers database';*/

        //if ($_SERVER['REQUEST_METHOD'] == 'POST') {

            //check passwords are equal

            if($_POST['password'] != $_POST['confirmpassword']){
                echo 'Passwords are not equal';
            }
            if ($_POST['password'] == $_POST['confirmpassword']){
                $sql = "INSERT INTO signup (Name, Surname, Email, Password) values ('$name', '$surname', '$email', '$password')";
        }

?>

预期结果是,如果密码相等,则数据将上传到mysql

1 个答案:

答案 0 :(得分:1)

您的代码有几个问题。首先,在正确的位置没有大括号,以确保您的比较在上下文中。您的连接检查应该有大括号:

if($con) {
   // your code here
}

解决此问题,然后需要执行查询。一种实现方法是使用mysqli_query()

$host= 'localhost';
$user= 'root';
$pass= '';
$db= 'newusers';

$name = $_POST['name'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$password = $_POST['password'];

$con=mysqli_connect($host,$user,$pass,$db);
if($con) { // added opening bracket here

    /*echo 'Connected Successfully to newusers database';*/

    //if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        //check passwords are equal
    //} added closing bracket here 

    if($_POST['password'] != $_POST['confirmpassword']){
        echo 'Passwords are not equal';
    } else { // you don't need another 'if' statement
        $sql = "INSERT INTO signup (Name, Surname, Email, Password) values ('$name', '$surname', '$email', '$password')";
        $result = mysqli_query($con, $sql); // execute the query
    }
}

警告!

Little Bobby your script is at risk for SQL Injection Attacks. 了解有关preparedMySQLi语句。甚至escaping the string都不安全!

切勿存储纯文本密码!!请使用 PHP的built-in functions 来处理密码安全性。如果您使用的PHP版本低于5.5,则可以使用password_hash() compatibility pack 在散列之前,无需escape passwords 或对它们使用任何其他清除机制。这样做更改密码并导致不必要的附加编码。

总是检查错误!

在打开<?php标签error_reporting(E_ALL); ini_set('display_errors', 1);后立即在文件顶部添加错误报告 向您的查询中添加错误检查,例如or die(mysqli_error($con))。或者,您可以在当前的错误日志中找到问题。