I'm trying to check if an Id already exists in table before I insert a duplicate.
So I need to check the table of database for the presence of the Id and if it exists then do nothing Otherwise I want to insert the record into the table. How can i do this?
Is there any other way except this:
Sql_query->Select id from table where key="something";
If(true)
{
do nothing;
}
else
{
Insert record in database;
}
I want to avoid this because it requires time to search entire table and then insert. So is there any feasible way?
Two strategies:
ON DUPLICATE KEY
if you want to do another table operation instead, if needed. Example:
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$result = $mysqli->query("SELECT id FROM yourtable");
if ($result->num_rows > 0) {
/* do your insert */
}
$result->close();
I prefer letting the database do the job.
Update:
On request here are two examples on how to add an unique index to your table. The SQL looks like this:
CREATE UNIQUE INDEX your index_name
ON your_table (your_id_field);
When inserting data, mysql will throw an error if the key already exists. To work with this error, do something like this:
$SQL = 'INSERT INTO yourtable (yourfield1, yourfield2)
VALUES ( 1, "Hello")';
$result = $mysqli->query($SQL);
if (!mysqli_query($link, $SQL)) {
if(mysqli_errno($link) == 1062) {
/* duplicate ... whatever you want in this case */
}
}
You don't need all this error handling if you don't want to do anything in this situation of course.
You can do that with the following code:
<?php
if($stmt = $db->prepare("SELECT * FROM tablename WHERE id=?")){
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows == 0){
// CREATE RECORD
}
}
?>
You just need to search in the table and check if the query returns something
Create unique index on a column (if you are not checking the primary key) and use ON DUPLICATE
when creatin SQL query. More about this: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
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.