简体   繁体   中英

Update database using MySQL and PHP

There are no errors shown when I click the register button to register new users, but the data isn't inserted in the database.

<?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";
    }
?>

check your else part you just created the query need to execute it

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



}

You forgot to execute your Insert query like below :

mysqli_query($link,$sql); 

But you have to use Prepared Insert Query to make it more secure:

// 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();

Just need to execute the query string like you did to check whether the user already exists or not.

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

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