php - mysqli insert - 但只有在不重复的情况下

标签 php mysql search insert mysqli

<分区>

我是一名 Java 开发人员,刚刚接到“一些快速简单的数据库操作”的任务——除了我对 PHP/MySQL 了解不多……我需要将一条记录插入数据库——但仅此而已如果电子邮件字段与数据库中已存在的字段不匹配。以下是我到目前为止为我的 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'");

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

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

有什么想法吗?

最佳答案

根据您的代码,这应该会为您指明正确的方向。也许有更好的方法来构建您的数据库,从而更好地利用它。

<?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;}
}

?>

关于php - mysqli insert - 但只有在不重复的情况下,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18008191/

相关文章:

c++ - 以下搜索算法的时间复杂度是多少?

php - PHP 中的日期差异?

php mysql左连接计数列相同的id

mysql - 为什么我可以读取 MySql 中的脏行

php - 自动完成 2 个查询

php查询搜索不稳定的结果

Python Flask 搜索 MySQL 数据库出现()

php - 通过用户操作在服务器上执行脚本

php - 乘法输入和显示的功能

mysql - 查询两个日期之间的小时和分钟