【发布时间】:2013-08-02 03:18:39
【问题描述】:
我是一名 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'");
现在我需要查看该搜索是否有任何返回 - 这意味着电子邮件已经存在 - 如果是,我需要提醒用户,否则我可以继续使用以下方法将新信息插入数据库:
$mysqli->query("INSERT INTO RegisteredUsersTable (UserName, UserEmail) VALUES ('".$newUserName."', '".$newUserEmail."')");
有什么想法吗?
【问题讨论】:
-
在数据库上设置
unique约束。然后最后从$mysqli->error读取,如果有错误,那就是重复了。 -
你到底在问什么?您想要更好的查询方式吗?还是您要求一些 PHP 代码将它们粘合在一起?
-
@MikeW:我相信他想在用户表中插入一些数据,而不是插入重复的数据(例如同一电子邮件的两行)。
-
对。我认为我到目前为止的代码还可以(也许不是最好的,但还可以) - 所以我只是缺少将它们粘合在一起的 if 语句的代码。
-
我的第一条评论有用吗?如果您决定对数据库进行验证,那么您只需访问数据库一次(使用 PHP)。
标签: php mysql search insert mysqli