mysqli insert-但仅当不是重复项时 [英] mysqli insert - but only if not a duplicate
问题描述
我是一名Java开发人员,刚刚完成了一些快速简单的DB任务"的任务-除非我对PHP/MySQL不太了解...我需要在DB中插入记录-但仅如果电子邮件字段与数据库中已存在的电子邮件字段不匹配.到目前为止,这是我为我的PHP代码所收集的内容:
I'm a Java developer who just got handed the task of "some quick easy DB stuff" - except I don't know much about PHP/MySQL...I need to insert a record into a DB - but only if the email field doesn't match one that already exists in the DB. Here's what I've gleaned so far for my PHP code:
// 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'");
现在,我需要查看搜索是否返回了任何内容-意味着电子邮件已经存在-如果需要,我需要提醒用户,否则,我可以继续使用以下命令将新信息插入数据库:
Now I need to see if anything came back from that search - meaning the email already exists - and if so I need to alert the user, otherwise I can go ahead and insert the new info into the DB using:
$mysqli->query("INSERT INTO RegisteredUsersTable (UserName, UserEmail) VALUES ('".$newUserName."', '".$newUserEmail."')");
有什么想法吗?
推荐答案
从您的代码开始,这应该为您指明正确的方向.也许有更好的结构来更好地利用数据库.
Working from your code, this should point you in the right direction. there are, perhaps, better ways to structure your database that will make better use of it.
<?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;}
}
?>
这篇关于mysqli insert-但仅当不是重复项时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!