I very frequently use logic something like this when writing to normalised databases.
In pseudocode:
is the thing I want in the table?:
yes - get it's ID
else
no - insert it, then get it's ID
In PHP:
// is the useragent in the useragent table?
// if so, find the id, else, insert and find.
$useragentResult = $mysqli->query("SELECT id FROM useragent WHERE name = '".$useragent."' LIMIT 1");
if ($useragentResult->num_rows == 0) {
// It is not in there
$mysqli->query("INSERT INTO useragent (name) VALUES ('".$useragent."')");
$resultID_object = $mysqli->query("SELECT LAST_INSERT_ID() as id");
$row = $resultID_object->fetch_object();
$useragentID = $row->id;
} else {
// It is, so find it and set it
$useragentData = $useragentResult->fetch_object();
$useragentID = $useragentData->id;
}
This feels ugly (not just due to PHP!), and common enough that perhaps there is a better way.
What’s the real way of doing this, or is this the best way?
Use
INSERT ... ON DUPLICATE KEY UPDATE.Since MySQL 5.5:
Or in earlier versions: