如何使用php准备好的语句防止重复的Mysql记录

我正在尝试使用准备好的语句来检查重复的记录,如果找到了重复的记录,则应将用户重定向到一个名为exist.php的页面。如果我将准备好的语句的顶部省略,则ELSE之后的部分工作正常。顶部根本不工作。有人可以帮我吗,这使我发疯。我一直在寻找解决方案已有2天了。谢谢。

这是准备好的语句之前的代码顶部,仅供参考:     

include(SHARED_PATH.'/connect.php');

 function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
// define variables and set to empty values
$nameErr = $emailErr = $websiteErr = $phoneErr = "";
$business_name = $email = $website = $phone = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {

 if (empty($_POST["business_name"])) {
   $nameErr = "Business Name is required";
   header("Location: required.php");
  } else {
   $business_name = test_input($_POST["business_name"]);
  }

  if (empty($_POST["email"])) {
    $email="";
  } else {
    $email = test_input($_POST["email"]);
    // check if e-mail address is well-formed
    if (!filter_var($email,FILTER_VALIDATE_EMAIL)) {
      $emailErr = 'Invalid email format';

    }
  }

  if (empty($_POST["website"])) {
    $website = "";
  } else {
    $website = test_input($_POST["website"]);
    // check if URL address syntax is valid (this regular expression also allows dashes in the URL)
    if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
      $websiteErr = "Invalid URL";
    }
  }

  if (empty($_POST["phone"])) {
   $phoneErr = "Phone is required";
   header("Location: required.php");
  } else {
    $phone = test_input($_POST["phone"]);
  }

因此,此行上方的所有内容均正常运行,我的问题从这里开始:

$stmt = $conn->prepare("SELECT * FROM dbname WHERE business_name = ? OR phone = ?");
$stmt->bind_param("ss",$business_name,$phone);

    // set parameters and execute
$business_name = $_POST['business_name'];
$phone = $_POST['phone'];
$stmt->execute();

if ($stmt->num_rows >0){
             header('Location: exists.php');
$stmt ->close();
} else{

    // prepare and bind
$stmt = $conn->prepare("INSERT INTO dbname (business_name,email,website,phone) VALUES (?,?,?)");
$stmt->bind_param("ssss",$email,$website,$phone);

// set parameters and execute
$business_name = $_POST['business_name'];
$email = $_POST['email'];
$website = $_POST['website'];
$phone = $_POST['phone'];
$stmt->execute();

$stmt ->close();
$conn ->close();
header('Location: add-to-list.php');
}

prepared语句的底部执行并毫无问题地将信息发送到数据库。准备好的语句的顶部不起作用。

fuyesunwang123 回答:如何使用php准备好的语句防止重复的Mysql记录

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/2981329.html

大家都在问