如何处理重复条目的错误?

问题描述 投票:0回答:7

我有一个 PHP 表单,可以将数据输入到我的 MySQL 数据库中。我的主键是用户输入的值之一。当用户输入表中已存在的值时,会返回 MySQL 错误“Duplicate entry 'entered value' for key 1”。 我想提醒用户他们需要输入不同的值,而不是出现该错误。只是一条回声消息或其他什么。

如何将特定的 MySQL 错误转换为 PHP 消息?

php mysql error-handling
7个回答
54
投票

要检查此特定错误,您需要找到错误代码

1062
表示重复密钥。然后使用
errno()
的结果与:

进行比较
mysqli_query('INSERT INTO ...');
if (mysqli_errno() == 1062) {
    print 'no way!';
}

关于编程风格的说明
您应该始终避免使用“幻数”(我知道,我是在这个答案中介绍它的人)。相反,您可以将已知的错误代码 (1062) 分配给常量(例如

MYSQLI_CODE_DUPLICATE_KEY
)。这将使您的代码更易于维护,因为当
if
的含义已从记忆中消失时,
1062
语句中的条件在几个月内仍然可读:)
    


5
投票
mysql_query

查看返回值。


$result = mysql_query("INSERT INTO mytable VALUES ('dupe')"); if (!$result) { echo "Enter a different value"; } else { echo "Save successful."; }



1
投票

$query = "INSERT INTO ".$table_name." ".$insertdata; if(mysqli_query($conn,$query)){ echo "data inserted into DB<br>"; }else{ if(mysqli_errno($conn) == 1062) echo "duplicate entry no need to insert into DB<br>"; else echo "db insertion error:".$query."<br>"; }//else end



0
投票
mysql_error()

函数 http://php.net/manual/en/function.mysql-error.php


0
投票
mysql_errno()

函数,它返回错误号。重复键的错误编号为 1062。 例如


$query = mysql_query("INSERT INTO table_name SET ...); if (mysql_errno() == 1062){ echo 'Duplicate key'; }



0
投票

function insertUserDetails($email, $conn){ try { $query = $conn->prepare ("INSERT INTO users (emailaddress) VALUES (:email)"); $query ->bindValue('email', $email); $query->execute(); } catch (PDOException $e) { if(str_contains($e, '1062 Duplicate entry')) { header("Location: login.php"); } die("Error inserting user details into database: " . $e->getMessage()); } }



0
投票
IGNORE 参数停止生成并出错,但仍然不允许重复输入。

$success = mysqli_stmt_execute($stmt); $affectedRows = mysqli_stmt_affected_rows($stmt); $newRowId = mysqli_insert_id($dbConn);

错误检查如果重复条目没有 php 或 mysql 引发错误

... /* ------------------------------------------------------- the function that will securely place the new data into the database table ------------------------------------------------------- */ function insertIntoDatabase($dbConn, $tablename, $userData) { /* Generate placeholders for prepared statement [$userData] is associate array ie "firstname" => "henry" with the part left of => being the exact database column name and the part right of => being value inserted in column */ $placeholders = rtrim(str_repeat('?, ', count($userData)), ', '); // Generate comma-separated list of column names $columns = implode(', ', array_keys($userData)); // Construct the SQL query for insertion $sql = "INSERT IGNORE INTO $tablename ($columns) VALUES ($placeholders)"; // Prepare the SQL statement $stmt = mysqli_prepare($dbConn, $sql); // Bind parameters to the prepared statement mysqli_stmt_bind_param($stmt, str_repeat('s', count($userData)), ...array_values($userData)); // Execute the prepared statement to insert data into the database mysqli_stmt_execute($stmt); /* feedback on success or faliure if [$affectedRows] = 0 and ][$newRowId] = 0 then we know nothing was added to database */ $affectedRows = mysqli_stmt_affected_rows($stmt); $newRowId = mysqli_insert_id($dbConn); return [$affectedRows, $newRowId]; }

参考
https://vb6code.com/code-php-insert-data-into-mysql-database.php

© www.soinside.com 2019 - 2024. All rights reserved.