Possible Duplicate:
Prevent Duplicate SQL entries
I’m just looking for a simple way to tell me if a record already exists, and if it does, not to insert it into the table. The below code inserts regardless if it exists or not… and I just cannot figure out why.
<?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 );
}
EDIT:
Ultimately, changing sqlsrv_num_rows($dup) > 0 to sqlsrv_has_rows($dup) fixed the problem. Below is my updated code:
$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 );
}
First, you need to identify your primary key. This is usually some sort of ID field. I’d probably recommend against using the pairing of FirstName LastName because there are many, many instances of people with the same first name and last name. “Kevin Kline” is the name of both an actor and a SQL Server MVP (and there are probably many, many more).
If you want to just blindly insert FirstName LastName into a table, then a RDBMS-agnostic query would be more like
(disclaimer: I know I didn’t format it according to what you had in your post, that is due to the following)
HOWEVER:
Your code is also vulnerable to SQL injection attacks. Please read up on the PHP method
sqlsrv_querypaying special attention to the “params” argument.Additionally, going back to the “Kevin Kline” example, this will only insert the first “Kevin Kline.” I suppose this is fine if you’re adding “Kevin Kline” as a dimension in a star schema that will be associated with other dimensions like Profession in a fact table. However, if that’s not your application domain, then I’d highly recommend that you determine what you’re going to use as your table keys so that you can accurately track the appropriate data.