I'm attempting to make a registration form for my assignments website, it should check if the email address given is already in the database and if its not insert the information and then return the customer id. If it is inside the database it should return the customer id as "exists" which sets of a front end error message. The problem is it seems to be inserting the information before it checks if it exists or not and so every new entry is returning "exists" instead of the users id. My PHP code is below.
<?php
$regemail = $_POST['regemail'];
$regfirst = $_POST['regfirst'];
$reglast = $_POST['reglast'];
$regcontact = $_POST['regcontact'];
$regline1 = $_POST['regline1'];
$regline2 = $_POST['regline2'];
$regline3 = $_POST['regline3'];
$regcity = $_POST['regcity'];
$regcounty = $_POST['regcounty'];
$regpost = $_POST['regpost'];
$regpass = $_POST['regpass'];
$customernumber = "";
//Open a new connection to the MySQL server
$mysqli = new mysqli('127.0.0.1','root','','u221062567_esl');
$results = $mysqli->query("SELECT * FROM customers WHERE `Email Address` = '$regemail'");
if($results ->num_rows > 0){
$customernumber = "exists";
}
else{
$regpass = md5($regpass);
$insertrow = $mysqli->query("INSERT INTO customers(`Email Address`, Password, `First Name`, `Last Name`, `Contact Number`, `Address Line 1`, `Address Line 2`, `Address Line 3`, `City/Town`, County, `Post Code`)VALUES('$regemail', '$regpass', '$regfirst', '$reglast', '$regcontact', '$regline1', '$regline2', '$regline3', '$regcity', '$regcounty', '$regpost');");
if($insertrow){
$results2 = $mysqli->query("SELECT * FROM customers WHERE `Email Address` = '$regemail'");
while($row2 = $results2->fetch_array()) {
$customernumber = $row2["Customer ID"];
}
}
else{
}
}
print json_encode($customernumber);
//Output any connection error
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
// close connection
$mysqli->close();
?>
Please help as I'm struggling to understand why its running the script in a non-sequential way. Many thanks.