使用MySQL和PHP更新数据库

时间:2017-12-05 04:39:07

标签: php mysql

单击注册按钮注册新用户时没有显示错误,但数据未插入数据库。

<?php
    session_start();
     if(isset($_POST['name'])&&isset($_POST['password'])){
    $name=$_POST['name'];
    $password=$_POST['password'];

    $link=mysqli_connect("localhost","root","");
    $select=mysqli_select_db($link,'first_db');
    $name=mysqli_real_escape_string($link,$name);
    $password=mysqli_real_escape_string($link,$password);
    $query="SELECT * FROM users WHERE name='$name'";
    $run=mysqli_query($link,$query);    
    $count = mysqli_num_rows($run);

    if ($count>0) {
    echo 'Sorry! This Username already exists!';
    } else {
        $name = $_POST['name'];
        $password=$_POST['password'];
        $sql = "INSERT INTO users (name, password)
                VALUES
                ('$_POST[name]','$_POST[password]')";
    }
     }
    else{
        echo"Cannot be blank";
    }
?>

3 个答案:

答案 0 :(得分:2)

检查你刚刚创建的其他部分查询需要执行它

if ($count>0)
{
   echo 'Sorry! This Username already exists!';
} 
else
{
    $name = $_POST['name'];
    $password=$_POST['password'];
    $sql = "INSERT INTO users (name, password)VALUES('$name','$password')";
    $run=mysqli_query($link,$sql);// add this statement then your record inserted



}

答案 1 :(得分:1)

您忘记执行如下所示的插入查询:

mysqli_query($link,$sql); 

但您必须使用准备好的插入查询来提高其安全性:

// prepare and bind User Query
$queryUsers = $conn->prepare("INSERT INTO 
users(name,password) VALUES (?, ?)");
$queryUsers->bind_param("ss",$name,$password);

$name = $_POST[name];
$password = $_POST[password];

// execute Users Query
$queryUsers->execute();

// Close Connections
$queryUsers->close();

答案 2 :(得分:0)

只需执行查询字符串就像检查用户是否已存在一样。

$sql = "INSERT INTO users (name, password)
            VALUES
            ('$_POST[name]','$_POST[password]')";
$run=mysqli_query($link,$sql);    // Executing the query here.