【问题标题】:PHP duplicate validation code not executing properlyPHP重复验证代码未正确执行
【发布时间】:2018-03-26 19:29:16
【问题描述】:

我试图防止重复的电子邮件输入,但代码不会运行“其他”部分。当重复电子邮件发生时,代码应该被执行 error.html 意味着相同的电子邮件已经在数据库中。

我尝试提供一个独特的电子邮件和一个重复的电子邮件。两次都发生了同样的问题,它重定向到 error.html 页面

<?php
require 'db_connect.php';

$conn = Connect();//function is on db_connect file
$value_fname = $conn->real_escape_string($_POST['fname']);
$value_lname = $conn->real_escape_string($_POST['lname']);
$value_email = $conn->real_escape_string($_POST['email']);


$sql = "SELECT count(email) FROM inquiry WHERE email='$value_email'";
$result = $conn->query($sql);
if (mysqli_num_rows($result) > 0) { // duplicate entry found
header('Location: error.html');
$conn->close();
} else {
$query = "INSERT INTO `inquiry` (`fname`,`lname`, `email`, 
`time_stamp`) VALUES ('$value_fname','$value_lname', '$value_email', 
CURRENT_TIMESTAMP)";
$success = $conn->query($query);

if (!$success) {
    header('Location: error.html');
    die("Couldn't enter data: " . $conn->error);
} else {
    $to = $value_email; // Send email to our user
    $subject = 'Signup | Examples'; // Give the email a subject
    $message = '
Hi ' . $value_fname . ',
Thanks for signing up!
Your email address has been recorded with us, you can now get
Latest information from us .

'; // Our message above including the link

    $headers = 'From:noreply@example.io' . "\r\n"; // Set from 
headers
    mail($to, $subject, $message, $headers); // Send our email
    header('Location: success.html');

}

}

$conn->close();

?>

【问题讨论】:

  • 您在email='value_email' 中缺少$ 吗?
  • 添加了 $value_email 但仍然是同样的问题
  • count() 查询将始终返回 1 行。您需要获取结果并查看该值是否为 0 或更大。
  • 谢谢,是的,你是对的

标签: php forms mysqli


【解决方案1】:

count() 在所有情况下都将返回一行,您可以在 if 语句中比较 count 的值或从查询中删除 count。第二种方法更简单,在最坏的情况下,查询将返回一行,因此性能几乎相同。

$sql = "SELECT email FROM inquiry WHERE email='$value_email'";

【讨论】:

  • 感谢我使用的是 double count 。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
  • 2014-01-08
  • 1970-01-01
  • 1970-01-01
  • 2018-03-12
相关资源
最近更新 更多