J Song J Song - 2 months ago 8
MySQL Question

Data is retrieved from DB but wont insert?

So when I want to retrieve data and check it i.e. if the email already exist echo already registered. That part works fine, however inserting the same data does not work. Are my conditionals ordered improperly?
(intentionally left out values for the dbhostname id pw variables)

$dbname = "hw2";

$link = mysqli_connect($dbhostname, $dbuserid, $dbpassword, $dbname);

$firstname = $_POST["signup-firstname"];
$lastname = $_POST["signup-lastname"];
$email = $_POST["signup-email"];
$password = $_POST["signup-password"];
$repassword = $_POST["signup-repassword"];

if ($password != $repassword){
echo "<br><h3>Passwords did not match. <br>Please try again.</h3>";
}

else {

$ret_email = "SELECT * FROM hw2 WHERE email = '$email'";
$result = mysqli_query($link, $ret_email);
$num_rows = mysqli_num_rows($result);

if ($num_rows > 0){
echo "This email is already registered.";
}

else{
$insert_query = "INSERT INTO hw2 (firstname, lastname, email, password, repassword) VALUES ('$firstname', '$lastname', '$email', '$password', '$repassword')";
echo "$insert_query";
}
}
?>

Answer

You should perform the query not only echoing it

mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age) 

if ($num_rows > 0){
echo "This email is already registered.";
}   

else{
$insert_query = "INSERT INTO hw2 (firstname, lastname, email, password, repassword) VALUES ('$firstname', '$lastname', '$email', '$password', '$repassword')";

echo "$insert_query";
mysqli_query($link,$insert_query)
}