可能的重复:
防止重复的 SQL 条目
我只是在寻找一种简单的方法来告诉我记录是否已经存在,如果存在,则不要将其插入表中。无论它是否存在,下面的代码都会插入......我只是不知道为什么。
<?php
$FirstName = $_POST["FirstName"];
$LastName = $_POST["LastName"];
$conn = sqlsrv_connect( $hostname, $connectionInfo)
$dup = sqlsrv_query($conn, "SELECT * FROM contact WHERE (FirstName='$FirstName') AND (LastName='$LastName')");
if(sqlsrv_num_rows($dup) > 0)
{
echo "Already Exists";
}
else
{
$query = "INSERT INTO contact (FirstName, LastName) VALUES ('$FirstName', '$LastName')";
sqlsrv_query( $conn, $query );
}
编辑:
最终,改变sqlsrv_num_rows($dup) > 0
以sqlsrv_has_rows($dup)
解决问题。以下是我更新的代码:
$params = array($_POST['FirstName'], $_POST['LastName']);
$conn = sqlsrv_connect( $hostname, $connectionInfo)
$sql = "SELECT * FROM contact WHERE FirstName = ? AND LastName = ?";
$dup = sqlsrv_query($conn, $sql, $params);
if(sqlsrv_has_rows($dup))
{
echo "Already Exists";
}
else
{
$query = "INSERT INTO contact (FirstName, LastName) VALUES (?, ?)";
sqlsrv_query( $conn, $query, $params );
}