简体   繁体   中英

INSERT INTO doesnt work php

I'm new to php.I'm trying to build a signup webpage in which if email entered doesn't exist it should insert the values entered.The code works fine and it returns successful when a new mail is entered.But the problem is when I check my database the new values are not inserted.Is there any mistake in my code? Thanks in advance.

<?php
session_start();
if(isset($_POST['signup'])){
include_once("db.php");

$email=strip_tags($_POST['emailid']);
$username=strip_tags($_POST['username']);
$password=strip_tags($_POST['password']);

if($email==NULL || $username== NULL || $password==NULL){

   print "Missing one of the fields";
}
else{

$email=stripslashes($email);
$username=stripslashes($username);
$password=stripslashes($password);

$email=mysqli_real_escape_string($db,$email);
$username=mysqli_real_escape_string($db,$username);
$password=mysqli_real_escape_string($db,$password);

$query = "SELECT * FROM user WHERE email='$email'";
$result = mysqli_query($db,$query);

if($result && mysqli_num_rows($result) > 0 )
{
echo "Account already exists.Please login";
}
else{
$sql="INSERT INTO user (ID,email,username,password) VALUES   
(NULL,'$email','$username','$password')";
if($sql)
{
echo "Account created successfully.";

}
else
{
echo "Error";

}
}
}
}
?>

You are not executing the insert query, it should look like:

$sql="INSERT INTO user (ID,email,username,password) VALUES   
(NULL,'$email','$username','$password')";
$sql= mysqli_query($db,$sql); ///You are missing this

Change from:

$sql="INSERT INTO user (ID,email,username,password) VALUES   
(NULL,'$email','$username','$password')";
if($sql)
{
echo "Account created successfully.";
}

To:

$sql="INSERT INTO user (ID,email,username,password) VALUES   
(NULL,'$email','$username','$password')";
if(mysqli_query($db,$sql))
{
echo "Account created successfully.";
}

You need to execute the 2nd query ( $sql )

$sql="INSERT INTO user (email,username,password) VALUES   
('$email','$username','$password')";
if(mysqli_query($db,$sql))
{
    echo "Account created successfully.";
}
  • Remove the null INSERT value it's not needed and should be auto generated if auto-incremental index.

  • execute the $sql statement aa MySQLi_query and then use the result of that in the IF statement.


Bonus: Use mysqli_error($db) to feed you back errors you will encounter, such as:

mysqli_query($db,$sql) or die("error: ".mysqli_error($db));

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