如何检查INSERT INTO id是否已经在数据库(PHP)中存在


How to check whether INSERT INTO id already exist in Database (PHP)

如何检查我计划插入到表中的ID是否已经存在?如果有,我该如何重复这个过程

$itemID = rand(1,99);
$itemName = $_POST['insert_item_name'];
$query = "INSERT INTO items (id, name) VALUES('$itemID', '$itemName')";

最简单的方法是先运行select命令进行检查,但这可能不是最好的解决方案。常见的方法是使用像auto_increment这样的列,这意味着您只需为该列插入null到表中,数据库将自动增加1。

例如,对于auto_increment列,您需要做的就是像这样插入:

insert into items (id, name) values (null, 'SomeName');

这将确保列是唯一的,并且永远不会有多个相同id的记录。

你也可以尝试像replace into这样的命令,如果行已经存在,它会用那个ID替换行。

replace into items(id, name) values (3,'SomeName');

这将插入一行到表中,如果没有的话,或者用查询中的新数据替换那里的内容-但是您需要确保列id在创建表时设置为唯一。

$aSql  = mysql_query("select count(*) from table where id = '$itemID'");
$iCnt = mysql_fetch_array($aSql);
if($iCnt > 0)
{
   echo "Id already exists";
}
else
{
  echo "insett new id";
}