简体   繁体   中英

How to check to see if a key exists before trying to insert it into a database?

I'm pulling data from a calendar feed and each event in the calendar has a unique $EventID string. I'm using PHP.

I have a SQL database with an Event_ID column. These IDs are strings. I need to be able to compare my $EventID against the Event_ID column and put in in the database if it's not there. I have a primary key set up to auto increment in the database, and I was thinking I can set up a loop to increment through those and compare each to the $EventID, but I'm wondering if there is a better way-maybe a PHP function I don't know about?

I've got a whole lot of code, but basically I've got:

<?php
$EventID = $event->id;  //This is the event ID

mysql_query("INSERT INTO myTable
              (Event_ID, Date_added, Date_edited)
             VALUES 
              ('$EventID', '$dateAdded', '$lastEdited')");

?>

So how do I set up a conditional to check all the Event_ID s that are already in the database against the $EventID ?

$query = "SELECT * FROM  `myTable`  WHERE `Event_ID`='$EventID' ";
    $result = mysql_query($query);
if (!mysql_num_rows($result))
 // INSERT QUERY

Check if the Event ID is present, If not insert it

You could just skip the "Select" query and do an "INSERT IGNORE" instead:

mysql_query("INSERT IGNORE INTO myTable
              (Event_ID, Date_added, Date_edited)
             VALUES 
              ('$EventID', '$dateAdded', '$lastEdited')");

this will leave existing Event_id's, and just add new records if required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM