在写入规范化数据库时,我经常使用类似这样的逻辑。
在伪代码中:
is the thing I want in the table?:
yes - get it's ID
else
no - insert it, then get it's ID
在 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;
}
这感觉很难看(不仅仅是因为 PHP!),而且很常见,也许有更好的方法。
这样做的真正方法是什么,或者这是最好的方法?