0

如何使用“电子邮件地址”作为提供错误的唯一重复条目?

我找到的很多答案都使用 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);
?>
4

2 回答 2

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);
?>
于 2013-05-02T10:05:56.660 回答
1

简单地emailaddress unique在你的桌子上做。

于 2013-05-02T09:45:00.900 回答