在插入

时间:2015-05-03 16:37:50

标签: php mysql duplicates

我需要创建一个收集名字,姓氏和电子邮件地址的表单。我在MySQL中创建了一个名为guestbook的表。该表格如下所示:

CREATE TABLE guestbook (
    id int unsigned NOT NULL AUTO_INCREMENT,
    firstName varchar(50) NOT NULL,
    lastName varchar(50) NOT NULL,
    email varchar(250) NOT NULL,
    status int NOT NULL,
    sort int NOT NULL
);

到目前为止,这是我的代码:

<?php

Global $Conn;
$Conn = new mysqli("localhost","151_millet","2gZMXYGC","GUESTBOOK");

if(!$Conn) {
    $ErrorMsg = "Couldn't connect to the database";
}

$FName = $_POST["fname"];
$LName = $_POST["lname"];
$Email = $_POST["email"];

// The series of ifs below tests to see if each field is blank
// If it is blank it will output an error message for each that is blank
if($FName == "") {
    $ErrorMsg .= "First Name Was Left Blank<br>";
}

if($LName == "") {
    $ErrorMsg .= "Last Name Field Was Left Blank.<br>";
}

if($Email == "") {
    $ErrorMsg .="Email field was left blank.<br>";
}

我不知道如何检查电子邮件字段中的重复项。任何帮助,将不胜感激。我想我需要想出一种方法来测试$ _POST以防止数据库中已有的内容。

1 个答案:

答案 0 :(得分:1)

好的,现在我们已经清理了这个问题了。让我们开始做生意。

您想要检查数据库中的重复项。你需要做几件事。让我们尽可能地保持这一点,同时我们也在努力。

首先,很高兴看到你使用的是MySQLi,而不是被弃用的mysql_ *函数。但是我们可以以更加面向对象的方式处理MySQLi。另外,使用全局变量是不受欢迎的(实际上没有必要,即使在你当前的代码中也是如此!)

另外需要注意的是,现代PHP中使用的代码风格略有不同,例如camel case,以及如何格式化if语句。如果您对学习PHP感兴趣,那么您应该看一下PHP-FIG PSR。

<?php

$conn = new mysqli("localhost", "151_millet", "2gZMXYGC", "GUESTBOOK");

if ($conn->connect_errno) {
    // This is an error that will stop us from continuing, so assigning
    // the error message to a string, doesn't really help us in this case
    // The application NEEDS to stop
    throw new RuntimeException("Unable to connect to MySQL database.");
}

$firstName = $_POST["fname"];
$lastName  = $_POST["lname"];
$email     = $_POST["email"];

if (!$firstName || !$lastName || !$email) {
    echo "Please make sure to fill in all of your details.";

    // You may want to handle this differently, this is just to keep things
    // Very simple
    exit;
}

$query = "SELECT COUNT(1) FROM guestbook WHERE email = ?";
$stmt = $conn->prepare($query);
$count = 0;

if ($stmt) {
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $stmt->store_result();

    $count = $stmt->num_rows;

    $stmt->close();
}

if ($count > 0) {
    echo "A user with that email address already exists.";
    exit;
}

// Do other stuff

这应该可以帮助您完成检查电子邮件地址是否已存在所需的操作。但是,您还应该通过向电子邮件列添加唯一密钥在数据库中强制执行此操作。这意味着即使您的代码失败并允许重复的电子邮件地址输入,您的数据库也不会。