$query = "INSERT IGNORE INTO `user` (`name`, `email`) VALUES ( '".$name."', '".$email."')";
$res = mysql_query($query) or die("Query failed ".mysql_error() );
$last id = mysql_insert_id();
mysql_insert_id() return 0 if there is a duplicated entry.
Is there a way to get the ID of the duplicated entry ? or do I have to do 2 query ( SELECT + INSERT ) ?
There is no way with an INSERT to get the ID of the existing (duplicate) entry.
Still, you should not do a SELECT + INSERT because you would need to lock the table for concurrency (to ensure that nothing has changed between SELECT and INSERT).
In this case, if the insert fails, and you want to update the existing record instead, use INSERT ... ON DUPLICATE KEY UPDATE.
If you just want to fail, but have the existing ID, then fail, and do a SELECT to get the existing entry.
Related
I have two tables first called messages and the other called messages_reply.
I used this code to insert into messages table:
$query = "INSERT INTO `messages` VALUES('', '$id', '$otherId', '')";
$query_run = mysqli_query($connect, $query);
I have the first column auto_increment thats why I left it empty by writing ''
Now i want this auto_increment value that i have inserted to be inserted in the other table called messages_reply
Do I have to create another query to return it or there is an instant way to insert it here and there?
you have to select the last id on table messages first, then you can insert that last id + 1 into messages reply
$query_sel_last_id = "SELECT id FROM messages ORDER BY id desc LIMIT 1"; // select the last id
after that, you only need to insert to messages_reply, remember to plus the value
$query_sel_last_id + 1
EDIT: gordon's solution is better and simpler, LAST_INSERT_ID()
I'm trying to update a record if the key is known else I want to insert it and get the inserted id, currently I have:
if(isset($data['applicationId']))
{
//update
$sql="
UPDATE myTable SET data='jsonstring' WHERE id = {$data['applicationId']}
";
}
else
{
//insert and get id
$sql="
INSERT INTO myTable SET data='jsonstring'
";
}
Is it possible to simplify the above to one query using INSERT ...ON DUPLICATE KEY UPDATE even when the key is not always known ?
I've tried this:
INSERT INTO myTable
(
id,
data
)
VALUES
(
?, # <- I may not know this!!
'jsonstring'
)
ON DUPLICATE KEY UPDATE
data = 'jsonstring'
Thanks for any suggestions.
Yes, you can do that, assumed id is your primary key and auto_increment. You will have two different queries, one if you know the applicationId and one when you not knowing it.
The first, when you know it:
INSERT INTO myTable
(
id,
data
)
VALUES
(
1337, # <- insert id
'jsonstring'
)
ON DUPLICATE KEY UPDATE
data = 'jsonstring';
And the one if the applicationId is unknown:
INSERT INTO myTable
(
id,
data
)
VALUES
(
NULL, # <- This will cause mysql to use a auto_increment value
'jsonstring'
)
ON DUPLICATE KEY UPDATE
data = 'jsonstring';
So you can conclude this to:
$sql="INSERT INTO myTable
(
id,
data
)
VALUES
(" .
isset($data['applicationId']) ? $data['applicationId'] : 'NULL'
.",
'jsonstring'
)
ON DUPLICATE KEY UPDATE
data = 'jsonstring';
";
But be aware of How can I prevent SQL-injection in PHP?
Happy coding
Please forgive because your question is not 100% clear. However, the concept I can tell is that you want to be able to ask more than 1 query on 1 sql statement. That can be done with a multi-query command. However, if you want some of your data from a query placed in your next query I do not think it will work. Link provided for multi_query
http://php.net/manual/en/mysqli.quickstart.multiple-statement.php
First, Simple update query will run. If it runs successfully, it will not go to if condition and your ID will be the one which was used in updating.
And, if that ID is not available (means update query fails, $Query will be false), so pointer jumps to if condition and insert the query. Now, new Inserted ID we can get.
$ID=$data['applicationId'];
$Query=mysql_query("UPDATE myTable SET data='jsonstring' WHERE id='$ID' ");
if(!$Query)
{
$InsertQuery=mysql_query("INSERT INTO myTable SET data='jsonstring'");
$ID=mysql_insert_id();
}
So, $ID will be your ID.(either updated or currently inserted)
I have an update.php form which is updating existing data. My problem is when I want to submit and part of my form is dynamic so they can add a new row to mysql while they are updating, so I keep getting duplicate dynamic rows in MySQL which are submitted before.
$i = 0;
while($i<count($fromhours)){
$fromhours[$i]= $fromhours[$i];
$fromminutes[$i]= $fromminutes[$i];
$tohours[$i]= $tohours[$i];
$tominutes[$i]= $tominutes[$i];
$resulthours[$i]= $resulthours[$i];
$resultminutes[$i]= $resultminutes[$i];
$hrscode[$i]= $hrscode[$i];
$gremark[$i]= $gremark[$i];
$query = "INSERT INTO `generalreport` (
`ID`, `date`, `fromhours`, `fromminutes`, `tohours`, `tominutes`, `resulthours`, `resultminutes`, `code`, `remark`
) VALUES (
'".$id."',
'".$date."',
'".$fromhours[$i]."',
'".$fromminutes[$i]."',
'".$tohours[$i]."',
'".$tominutes[$i]."',
'".$resulthours[$i]."',
'".$resultminutes[$i]."',
'".$hrscode[$i]."',
'".$gremark[$i]."'
);";
mysql_query($query);
$i++;
};
How can I use this code for update and just insert new data in MySQL and old data won't be duplicated.
i think you have to index your table in mysql such that if any new data enters that have any similar date and entry the mysql will automatically pop out a duplicate entry error
Use
INSERT INTO `generalreport` (
`ID`, `date`, `fromhours`, `fromminutes`, `tohours`, `tominutes`, `resulthours`, `resultminutes`, `code`, `remark`
) VALUES (...),(...),(...)
I have an assosiative array in PHP which is inserting data into a table
foreach($array as $key => $value){
$query = "INSERT INTO live_list (file_id, date) SELECT ('$key', '$value') FROM dual WHERE NOT EXISTS (SELECT * FROM live_list WHERE file_id = '$key')";
mysqli_query($link, $query) or die('Query failed: ' . mysqli_error($link));
}
However as I have moved from an indexed array to an assosiative array, I can't figure out how to insert this data ONLY if the data in my array does not exist in my table.
Query failed: Operand should contain 1 column(s)
Now I am recieving this error
Any help will be great!
Why the use of a sub-query?
Assuming file_id is a unique field (i.e. no duplicates in the whole table), make it a unique index on the table if it isn't already:
ALTER TABLE live_list
ADD UNIQUE (file_id)
and change your query to
INSERT INTO live_list (file_id, date)
VALUES ('$key', '$value')
ON DUPLICATE KEY UPDATE date = date;
This means that it will simple "update" the value of date to what it already is if it encounters a duplicate key.
Although you should look to bind your parameters to protect against sql injection.
You could do this:
INSERT INTO live_list (file_id, date)
SELECT '$key', '$value'
FROM dual
WHERE NOT EXISTS (SELECT * FROM live_list WHERE file_id = '$key')
DUAL is a dummy table. The logic is that if the sub query does not exist, the dummy table returns one row with the desiered input.
I'm pulling data from a calendar feed and each event in the calendar has a unique $EventID string. I'm using PHP.
I have a SQL database with an Event_ID column. These IDs are strings. I need to be able to compare my $EventID against the Event_ID column and put in in the database if it's not there.
I have a primary key set up to auto increment in the database, and I was thinking I can set up a loop to increment through those and compare each to the $EventID, but I'm wondering if there is a better way-maybe a PHP function I don't know about?
I've got a whole lot of code, but basically I've got:
<?php
$EventID = $event->id; //This is the event ID
mysql_query("INSERT INTO myTable
(Event_ID, Date_added, Date_edited)
VALUES
('$EventID', '$dateAdded', '$lastEdited')");
?>
So how do I set up a conditional to check all the Event_IDs that are already in the database against the $EventID?
$query = "SELECT * FROM `myTable` WHERE `Event_ID`='$EventID' ";
$result = mysql_query($query);
if (!mysql_num_rows($result))
// INSERT QUERY
Check if the Event ID is present, If not insert it
You could just skip the "Select" query and do an "INSERT IGNORE" instead:
mysql_query("INSERT IGNORE INTO myTable
(Event_ID, Date_added, Date_edited)
VALUES
('$EventID', '$dateAdded', '$lastEdited')");
this will leave existing Event_id's, and just add new records if required.