mysqli插入 - 但只有不重复

sir*_*333 0 php mysql search mysqli insert

我是一名Java开发人员,他只是接受了"一些快速简单的DB内容"的任务 - 除了我对PHP/MySQL不太了解...我需要在数据库中插入一条记录 - 但仅限于电子邮件字段与DB中已存在的字段不匹配.这是我到目前为止为我的PHP代码收集的内容:

// Grab the values from the HTML form:
$newUserName = $_POST['newUserName'];
$newUserName = $mysqli->real_escape_string($newUserName);
$newUserEmail = $_POST['newUserEmail'];
$newUserEmail = $mysqli->real_escape_string($newUserEmail);

// Now search the DB to see if a record with this email already exists:
$mysqli->query("SELECT * FROM RegisteredUsersTable WHERE UserEmail = '$newUserEmail'");
Run Code Online (Sandbox Code Playgroud)

现在我需要查看是否有任何内容从该搜索返回 - 这意味着电子邮件已经存在 - 如果是这样,我需要提醒用户,否则我可以继续使用以下内容将新信息插入到数据库中:

$mysqli->query("INSERT INTO RegisteredUsersTable (UserName, UserEmail) VALUES ('".$newUserName."', '".$newUserEmail."')");
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

kmo*_*y12 6

考虑unique在此特定表上放置索引.以下代码将添加索引并删除任何当前重复项:

ALTER IGNORE TABLE `RegisteredUsersTable` ADD UNIQUE INDEX unique_email (`UserEmail`);
Run Code Online (Sandbox Code Playgroud)

添加后,使用INSERT IGNOREINSERT...ON DUPLICATE KEY UPDATE.如果没有重复,他们只会预先插入插入.

$mysqli->query("INSERT IGNORE INTO RegisteredUsersTable (UserName, UserEmail) VALUES ('".$newUserName."', '".$newUserEmail."')");
Run Code Online (Sandbox Code Playgroud)

Mysql会抛出错误,因为电子邮件已经存在于数据库中.但是,IGNORE命令告诉脚本不要注意此查询的错误,因为在这种情况下,您希望它对于重复的行.

此外,有一种方法可以向用户发出失败或成功消息,即使是INSERT IGNORE.使用MYSQL LAST_INSERT_ID().如果给出了ID,则将其插入.如果没有,那么电子邮件已经存在(或者还有其他错误).


小智 6

使用您的代码,这应该指向正确的方向.或许,有更好的方法来构建数据库,以便更好地利用它.

<?php

$mysqli = new mysqli("localhost", "iodine", "iodine","iodine");

// Grab the values from the HTML form:
/*
$newUserName = $_POST['newUserName'];
$newUserName = $mysqli->real_escape_string($newUserName);
$newUserEmail = $_POST['newUserEmail'];
$newUserEmail = $mysqli->real_escape_string($newUserEmail);
*/
$newUserName = "Test User";
$newUserEmail = "test4@example.com";

// Now search the DB to see if a record with this email already exists:
echo "SELECT * FROM RegisteredUsersTable WHERE UserEmail = '$newUserEmail'", "\n";
$result = $mysqli->query("SELECT * FROM RegisteredUsersTable WHERE UserEmail = '$newUserEmail'");

if (!$result) {
  die($mysqli->error);
}
echo "num_rows = ".$result->num_rows."\n";
if ($result->num_rows > 0) {
   echo "Duplicate email\n";
   // do something to alert user about non-unique email
} else {
  $result = $mysqli->query("INSERT IGNORE INTO RegisteredUsersTable (UserName, UserEmail) VALUES ('".$newUserName."', '".$newUserEmail."')");
  if ($result === false) {echo "SQL error:".$mysqli->error;}
}

?>
Run Code Online (Sandbox Code Playgroud)