PHP:向表插入相同值时死亡

时间:2019-06-03 19:57:26

标签: php mysql ajax

我有一个简单的代码,当值不在表中时会插入值

我试图制作代码,其中未将值插入表脚本时死了,或者尝试执行其他操作以显示例如“值已插入”,但我的代码不起作用。脚本仅当不在表中时才添加值,而当值在表中时才添加值,并且脚本继续发出AJAX请求。也许当ajax完成(将值添加到表中)而ajax失败(未添加值)并做出其他不相关的事情时。

$emaildb = mysqli_connect("localhost", "root", "root", "dbdbdb");

if($emaildb === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}

$email = mysqli_real_escape_string($emaildb, $_REQUEST['email']);

$sql = "INSERT INTO emails (email)
        SELECT '$email'
        FROM DUAL
        WHERE NOT EXISTS 
            (SELECT 1
            FROM emails
            WHERE email = '$email')
        LIMIT 1";

$result = mysqli_query($emaildb, $sql);

while($row = mysqli_fetch_object($result)) {
    if (isset($row->blocked)) {
        die('Denied!');
    } else {
        echo 'Access!';
    }
}

mysqli_close($emaildb);

2 个答案:

答案 0 :(得分:0)

您可以使用mysqli_insert_id,如果未插入任何内容,它将返回0:

<?php

$emaildb = mysqli_connect("localhost", "root", "root", "dbdbdb");

if(!$emaildb) {
    die("ERROR: Could not connect. " . mysqli_connect_error());
}

$email = mysqli_real_escape_string($emaildb, $_REQUEST['email']);

$sql = "INSERT INTO emails (email)
        SELECT '$email'
        FROM DUAL
        WHERE NOT EXISTS 
            (SELECT 1
            FROM emails
            WHERE email = '$email')
        LIMIT 1";

$result = mysqli_query($emaildb, $sql);
if(mysqli_insert_id($emaildb) == 0) {
    echo "DIE!";
} else {
    echo "Access";
}

mysqli_close($emaildb);

答案 1 :(得分:0)

像您这样的正确SELECT和INSERT方案看起来像这样:

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // enable exception mode
$mysqli = new mysqli("localhost", "dbuser", "dbpass", "test");

if ($mysqli->connect_errno) {
    throw new \Exception("ERROR: Could not connect. " . $mysqli->connect_error);
}

if (isset($_REQUEST['email'])) {
    $selectStmt = $mysqli->prepare('SELECT COUNT(1) FROM emails WHERE email=?');
    $selectStmt->bind_param('s', $_REQUEST['email']);
    $selectStmt->execute();
    $found = $selectStmt->get_result()->fetch_array()[0];
    if ($found) {
        echo 'This email already exists!';
    } else {
        $insertStmt = $mysqli->prepare('INSERT INTO emails(email) VALUES (?)');
        $insertStmt->bind_param('s', $_REQUEST['email']);
        $insertStmt->execute();

        echo 'Email has been added';
    }
}

我使用了准备好的语句并执行了两个单独的查询。为了简化起见,我还启用了MySQLi异常模式。
此代码将首先检查电子邮件是否存在于数据库中,如果不存在,它将尝试将其插入。尝试避免在代码中插入die(),这绝不是一个好习惯。

此代码示例不包含AJAX。您需要对此进行调整以适合您的特定应用程序并实施一些错误检查。该代码仅用于显示建议的执行SQL语句的方式。