如何使用“emailaddress”作为唯一提供错误的重复条目?
我发现很多答案都使用mysql_query,但我想使用mysqli。
<?php
$con=mysqli_connect("localhost","","","");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO entry (firstname, lastname, emailaddress, favoritesong) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[emailaddress]','$_POST[favoritesong]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
答案 0 :(得分:2)
警告!已发布的代码和此答案(因为我现在只解决问题)包含大量SQL注入泄漏。请阅读SQL注入并使用转义或准备好的语句。
<?php
$con = mysqli_connect("localhost", "", "", "");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
$existsQuery = "select count(*) as count from entry where emailaddress like '".$_POST[emailaddress]."'";
$existsResult = mysqli_query($con, $existsQuery);
if($existsResult->fetch_object()->count > 0)
{
echo "email already exist";
}
else
{
$sql = "INSERT INTO entry (firstname, lastname, emailaddress, favoritesong) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[emailaddress]','$_POST[favoritesong]')";
if (!mysqli_query($con, $sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
}
mysqli_close($con);
?>
答案 1 :(得分:1)
只需在表格中设置emailaddress
unique
即可。