質問

How do I check whether the ID which I am planning to insert to my table already exist? And if so how do I repeat the process

$itemID = rand(1,99);
$itemName = $_POST['insert_item_name'];

$query = "INSERT INTO items (id, name) VALUES('$itemID', '$itemName')";
役に立ちましたか?

解決

The simplest way to do what you want is to run a select first to check - but that might not be the best solution. The common approach is to use a column such as auto_increment which means you just insert a null into the table for that column and the database will increment by one automatically.

Eg, with an auto_increment column, all you need to do is insert like this:

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

This will ensure that the column is unique and will never end up with multiple records for the same id.

You can also try something like replace into which will replace the row if it is there already with that ID.

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

This will insert a row into the table if there isn't one, or replace what is there with the new data in your query - but you need to ensure that the column id is set to unique when creating the table.

他のヒント

$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";
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top