我试图为我的作业网站制作一个注册表格,它应该检查给定的电子邮件地址是否已经在数据库中,如果它没有插入信息,然后返回客户ID。如果它在数据库中,它应该返回客户ID为"存在"哪一组前端错误消息。问题是它似乎是在检查信息是否存在之前插入信息,因此每个新条目都返回"存在"而不是用户ID。我的PHP代码如下。
<?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();
?>
请帮助我,因为我正在努力理解为什么它以非顺序的方式运行脚本。非常感谢。
答案 0 :(得分:0)
你应该使用预准备语句来避免sql注入,无论如何尝试以下代码
function checkEmail($email){
$stmt = $db->prepare("SELECT email from `customers` where email_address = ?");
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows < 1){
return true;
}
return false;
}
function addCustomer($regemail, regfirst, reglast....){
$stmt = $db->prepare("insert into `customers` (email_address, password, first_name, last_name...)" values(?,?,?,?...));
$stmt->bind_param('ssss', $regemaail, $hash, $regfirst, $reglast....);
$stmt->execute();
if($stmt->afffected_rows > 0){
return $stmt->insert_id;
}
return false;
}
然后调用函数
if(checkEmail($_POST['email'])){
$customer_number = addCustomer($regemail,...);//this will give you id of the insert, you can do another query using this number I guess since I don't understand why you need it.
if($customer_number){
//another query
}
}
else{
//email exists
}