我有一个表单,在您提交后会显示感谢信息,但是,如果您提交的电子邮件已经存在于数据库中,我希望它提醒“无效电子邮件”。
现在,即使电子邮件已经存在于数据库中,它也只会转到感谢信息(并且不显示警报)。我使用ajax将表单数据发送到数据库。我在代码中做错了什么?
我的ajax代码:
$(document).ready(function(){
$("#submit").click(function(){
var name = $("#fullname2").val();
var email = $("#fullemail2").val();
var state = $("#selectstate").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'FullName='+ name + '&email='+ email + '&SovereignState='+ state;
if(name==''||email==''||state=='')
{
alert("Please Fill All Fields");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "demo.php",
data: dataString,
cache: false,
success: function( phpSays ){
if ( phpSays == "OK"){
alert("invalid email");
}
else {
$('#sinatra2').hide();
$('#thanks').show();
}
}
});
}
return false;
});
});
这是php:
<?php
define('DB_NAME', '');
define('DB_USER', '');
define('DB_PASSWORD','');
define('DB_HOST', '');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) ;
if (!$link) {
die('Could not connect: ' . mysql_error ()) ;
}
$db_selected = mysql_select_db (DB_NAME, $link) ;
if (!$db_selected) {
die('Cant use ' . DB_NAME . ': ' . mysql_error()) ;
}
$new_email = $_POST ['email'];
$sql2 = mysql_query ("SELECT email from Data_2 WHERE email = '$new_email");
$row = mysql_fetch_row($sql2);
if(mysql_num_rows($row) > 0) {
echo 'OK' ;
}
else {
$value = $_POST ['FullName'];
$value2 = $_POST ['email'];
$value3 = $_POST ['SovereignState'];
$sql = "INSERT INTO Data_2 (FullName, email, SovereignState) VALUES ('$value', '$value2', '$value3')";
if (!mysql_query ($sql)) {
die('Error: ' . mysql_error());
}
}
mysql_close();
?>
答案 0 :(得分:0)
试试这个:
$sql2 = mysql_query("SELECT COUNT(`email`) AS count from Data_2 WHERE email = $new_email");
if ($sql2)
{
$count = mysql_fetch_assoc($sql2) ['count'];
if ($count > 0)
{
echo 'email exists';
}
else
{
echo 'email does not exist';
}
}
答案 1 :(得分:0)
您错过了SQL中的结尾引用。您需要转义电子邮件以防止SQL注入。你使用mysql_num_rows()错误,它接受资源。以下是修复所有问题的示例:
$result = mysql_query ("SELECT email from Data_2 WHERE email = '".mysql_real_escape_string($new_email)."'");
if (mysql_num_rows($result) > 0) {
echo 'OK' ;
}
答案 2 :(得分:0)
$sql2 = mysql_query ("SELECT email from Data_2 WHERE email = '$new_email");
替换为:
$sql2 = mysql_query ("SELECT email from Data_2 WHERE email = '$new_email' ");
另外
if(mysql_num_rows($row) > 0) {
echo 'OK' ;
}
替换为:
if(mysql_num_rows($sql2) > 0) {
echo 'OK' ;
}
答案 3 :(得分:0)
将此行var dataString = 'FullName='+ name + '&email='+ email + '&SovereignState='+ state;
替换为var dataString = {FullName: name, email: email, SovereignState: state};
。可以解决问题的家。