我只是在尋找一種簡單的方法來告訴我,如果一個記錄已經存在,如果確實如此,不要將其插入表格中。下面的代碼插入,無論它是否存在或不......我只是不明白爲什麼。
<?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);
}
嘗試'選擇*從聯繫人WHERE FirstName ='$ FirstName'AND LastName ='$ LastName''作爲檢查。 –