我有一个 PHP 表单,可以将数据输入到我的 MySQL 数据库中。我的主键是用户输入的值之一。当用户输入表中已存在的值时,会返回 MySQL 错误“Duplicate entry 'entered value' for key 1”。 我想提醒用户他们需要输入不同的值,而不是出现该错误。只是一条回声消息或其他什么。
如何将特定的 MySQL 错误转换为 PHP 消息?
mysql_query
查看返回值。
$result = mysql_query("INSERT INTO mytable VALUES ('dupe')");
if (!$result) {
echo "Enter a different value";
} else {
echo "Save successful.";
}
$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
mysql_errno()
函数,它返回错误号。重复键的错误编号为 1062。 例如
$query = mysql_query("INSERT INTO table_name SET ...);
if (mysql_errno() == 1062){
echo 'Duplicate key';
}
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());
}
}
$success = mysqli_stmt_execute($stmt);
$affectedRows = mysqli_stmt_affected_rows($stmt);
$newRowId = mysqli_insert_id($dbConn);
...
/* -------------------------------------------------------
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