MySQL:具有相同连接对象的多个查询

时间:2014-07-10 19:14:45

标签: php mysql

我有一个我的网站的注册脚本,我首先检查用户输入的电子邮件是否与数据库中的电子邮件匹配,如果匹配,则返回找到匹配项并且不插入新帐户进入数据库。

- 我想知道是否有办法用一个mysql连接对象完成我正在做的事情,而不是初始化其中两个?

- 此外,我觉得我的代码非常混乱,并且会更喜欢如何更好地编写代码。谢谢!

注意: 将来会使用验证布尔值,因此请忽略它无效的事实。

<?php
include '../portfolio/libraries/settings.php';

$first = $_POST['first'];
$middle = $_POST['middle'];
$last = $_POST['last'];
$email = $_POST['email'];

$emailFound = false;
$validation = true;

if ($_POST['type'] == "Student") {
    $type = "0";
} else {
    $type = "1";
}

$connect = mysqli_connect($HOST, $DB_USER, $DB_PASS, $DATABASE);
$connect1 = mysqli_connect($HOST, $DB_USER, $DB_PASS, $DATABASE);

$result = $connect1->prepare("SELECT email FROM AUTH_User WHERE email = ?");
$result->bind_param("s", $email);
$result->execute();

while($result->fetch()) {
    $emailFound = true;
}

if (!$emailFound) {
    if ($middle != "" || $middle != null) {
        $query = "INSERT INTO AUTH_User (email, FirstName, MiddleName, LastName, is_faculty) VALUES (?, ?, ?, ?, ?)";
        $stmt = $connect->prepare($query);
        $stmt->bind_param("ssssi", $email, $first, $middle, $last, $type);

        if ($stmt->execute() && $validation) {
            echo "success";
        }
    } else {
        $query = "INSERT INTO AUTH_User (email, FirstName, LastName, is_faculty) VALUES (?, ?, ?, ?)";
        $stmt = $connect->prepare($query);
        $stmt->bind_param("sssi", $email, $first, $last, $type);

        if ($stmt->execute() && $validation) {
            echo "success";
        }
    }
} else {
    echo "found";
}

?>

1 个答案:

答案 0 :(得分:2)

您只能使用一个$ connect:)

也许我可以建议您使用PDO进行查询:http://php.net/manual/en/book.pdo.php

我试图用我自己的经验来清除你的代码,所以我没有更好的编码方式;)

include '../portfolio/libraries/settings.php';

$first = $_POST['first'];
$middle = $_POST['middle'];
$last = $_POST['last'];
$email = $_POST['email'];  
$emailFound = false;
$validation = true;

$type = ($_POST['type'] == "Student")? 0 : 1 ;

$connect = mysqli_connect($HOST, $DB_USER, $DB_PASS, $DATABASE);

$result = $connect->prepare("SELECT email FROM AUTH_User WHERE email = ?");
$result->bind_param("s", $email);
$result->execute();

if(!$result->fetch()) {
    if (isset($middle)) {
        $query = "INSERT INTO AUTH_User (email, FirstName, MiddleName, LastName, is_faculty) VALUES (?, ?, ?, ?, ?)";
        $stmt = $connect->prepare($query);
        $stmt->bind_param("ssssi", $email, $first, $middle, $last, $type);

        if ($stmt->execute() && $validation)
            echo "success";

    } else {
        $query = "INSERT INTO AUTH_User (email, FirstName, LastName, is_faculty) VALUES (?, ?, ?, ?)";
        $stmt = $connect->prepare($query);
        $stmt->bind_param("sssi", $email, $first, $last, $type);

        if ($stmt->execute() && $validation)
            echo "success";
    }
} else {
    echo "found";
}