我试图在插入数据之前检查数据库中是否已存在电子邮件。
这是我的代码:
<?php
$servername = "servername";
$username = "username";
$password = "password";
$dbname = "dbname";
$Mail = $_POST['email'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Inputed in E-Mail Field
$Mail = $_POST['email'];
$SearchEmail = $conn->query("SELECT (Mail) FROM betakey WHERE Mail = '$Mail'");
if ($SearchEmail->num_rows > 0) {
print "That Email is already registered for the closed alpha";
}
else {
$conn->query("INSERT INTO betakey VALUES ('$Mail')");
}
$conn->close();
?>
当我访问该页面时,它并没有给我任何错误,但它也没有回应它存在或在数据不存在时插入数据。
答案 0 :(得分:1)
问题在于您的插入查询。插入查询的结构总是如下所示。
INSERT INTO table_name(column1,column2,column3,...) VALUES(value1,value2,value3,...) 请参阅:http://www.w3schools.com/php/php_mysql_insert.asp
将此应用于您的代码,会产生以下结果。
<?php
$servername = "servername";
$username = "username";
$password = "password";
$dbname = "dbname";
$Mail = $_POST['email'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Inputed in E-Mail Field
$Mail = $_POST['email'];
$SearchEmail = $conn->query("SELECT count(Mail) FROM betakey WHERE Mail = '$Mail'");
if ($SearchEmail->num_rows > 0) {
print "That Email is already registered for the closed alpha";
}
else {
$conn->query("INSERT INTO betakey (Mail) VALUES ('$Mail')");
}
$conn->close();
?>
我建议你带走两个'$ Mail = $ _POST ['email']中的一个;',因为以相同的方式两次声明一个变量是没用的。