I have two tables cw_users and ref_users, both have a column named id.
I'm using ISAM so can't use a foreign key.
So now I wanted to insert id from cw_users into ref_users if it didn't exist.
This is what I did, but didn't help:
$id = $_SESSION['id'];
$ref_code=md5($id);
mysql_query("INSERT INTO ref_users (id) VALUES ('$id') WHERE NOT EXISTS (SELECT FROM cw_users where id='$id')");
The correct syntax is INSERT IGNORE INTO
INSERT IGNORE INTO ref_users (id)
VALUES ('$id')
It will insert if the value does not exist, and ignore the statement if it does.
Note that this will only work if id is the Primary Key
EDIT: It seems from your comments that you would be much better off using ON DUPLICATE KEY UPDATE.
Try this query
INSERT INTO ref_users(id, ref_code)
VALUES ('$id', '$ref_code')
ON DUPLICATE KEY UPDATE
ref_code = '$ref_code'
...WHERE NOT EXISTS (SELECT id FROM ...
why not run normal insert, it will fail if row exists?
Your query is
"INSERT INTO ref_users (id) VALUES ('$id') WHERE NOT EXISTS (SELECT FROM cw_users where id='$id')"
You can't use were case in insert query . you can use normal insert .
Related
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.
Let me explain what I need and canot get :(
I have to DB one i main the other is just getting part of data from the firs one.
This is my code:
foreach($id_product_array AS $id_product) {
$resultf = mysql_query("SELECT * FROM db1_available_product WHERE id_product='".$id_product."'");
while($rowi = mysql_fetch_array($resultf)) {
$aa1=$rowi['id_product'];
$aa2=$rowi['date'];
$aa3=$rowi['available'];
$aa4=$rowi['published'];
mysql_query("INSERT INTO aa_bb.db2_available_product (`id_product`, `date`, `available`, `published`) VALUES ('".$aa1."','".$aa2."', '".$aa3."', '".$aa4."') ON DUPLICATE KEY UPDATE `id_product` = '".$aa1."', `date` = '".$aa2."', `available` = '".$aa3."', `published` = '".$aa4."'");
}
The problem is that this multiples the record in DB2 so I am now in millions!!!
Its set up as cron job on 1h basis.
What I need is ether it checks what is existing and don't touch it or if need on update or insert.
The other solution would be to delete the whole table in DB2 then to insert a fresh one from DB1
You can simplify your query like so:
INSERT INTO tbl2 (column1, column2)
SELECT column1, column2 FROM tbl1
ON DUPLICATE ...
See the documentation
You are looking for MySQL's proprietary REPLACE command. It has the same syntax as a regular INSERT, but it checks for duplicate primary key before inserting, and if it is found it will do an UPDATE instead:
REPLACE works exactly like INSERT, except that if an old row in the
table has the same value as a new row for a PRIMARY KEY or a UNIQUE
index, the old row is deleted before the new row is inserted.
Of course you will have to define a unique PK/index on your table that allows this functionality to work.
here is an update!
I solved the problem :)
Thanks s to Niels because he made me rethink my strategy so the solution was simple.
In the DB1 and DB2 there is and ID filed
A added
$aa5=$rowi['id'];
so that made ON DUPLICATE KEY UPDATE work correctly!
foreach($id_product_array AS $id_product) {
$resultf = mysql_query("SELECT * FROM db1_available_product WHERE id_product='".$id_product."'");
while($rowi = mysql_fetch_array($resultf)) {
$aa5=$rowi['id'];
$aa1=$rowi['id_product'];
$aa2=$rowi['date'];
$aa3=$rowi['available'];
$aa4=$rowi['published'];
mysql_query("INSERT INTO aa_bb.db2_available_product (`id`,`id_product`, `date`, `available`, `published`) VALUES ('".$aa5."','".$aa1."','".$aa2."', '".$aa3."', '".$aa4."') ON DUPLICATE KEY UPDATE `id` = '".$aa5."',`id_product` = '".$aa1."', `date` = '".$aa2."', `available` = '".$aa3."', `published` = '".$aa4."'");
}
and it seams that it is working OK!
:)
Instead of finding that a row exists where 'bookName' equals 'bookName' and just updating, it creates a brand new row. What is wrong with my command? thanks!
$query = mysql_query(
"INSERT INTO custombookinfo (userId, sendToAddress, work, caseStudies, url, entryPoint, date, bookName)
VALUES ('$userId', '$emailAddress', '$work', '$caseStudies', '$url', '$entryPoint', '$date', '$bookName')
ON DUPLICATE KEY UPDATE bookName = 'bookName'"
);
the INSERT query is correct but I think you have failed to define UNIQUE constraint on column bookName. Execute the following statement:
ALTER TABLE custombookinfo ADD CONSTRAINT tb_uq UNIQUE (bookName);
Depending on what you want to be UNIQUE in the table, you should create an index (PRIMARY or UNIQUE) for whether user_id, or bookName.
More details about INSERT ... ON DUPLICATE KEY UPDATE http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
I want to insert into a MySQL row if the row doesn't exist, or update it if it does exist.
Something like this:
$sqlQuery = "INSERT INTO table (Value1, Value2) VALUES ('$var1', '$var2') WHERE UniqueKey='$id'";
Is something like that possible?
INSERT INTO table (UniqueKey,Value1, Value2) VALUES ('$id','$var1', '$var2')
ON DUPLICATE KEY UPDATE Value1 = '$var1',Value2 = '$var1';
User MySQL's REPLACE command:
$sqlQuery = "REPLACE INTO table (id, Value1, Value2) VALUES ('$id', '$var1', '$var2')";
It works the same as a normal INSERT, but if the primary key (in you case 'id') matches then it will replace all the values specified.
replace into table (UniqueKey,Value1,Value2) values ('$id','$var1','$var2');
replace is similar to insert, however if the unique key exists in table, it will delete first, and than insert.
Hey guys quick question, I currently have an insert statement
$query= "INSERT into new_mail VALUES ('$to1', '0')"; where fields are username, and message_number
Currently what I would do to check if the entry exists, is do a select query then check the number of rows with mysql_num_rows (php). If rows==1 then I get the current message_number and set it equal to
$row['message_number']+1.
Then I update that entry with another query.
Is there an easier way to do all this in just mysql with just one query (check if exists, if not insert, if so update message_number, increase by 1)?
Depending on how your table is structured, you may be able to use the ON DUPLICATE KEY UPDATE (link to the MySQL manual) feature of INSERT:
INSERT into new_mail VALUES ('$to1', '0') ON DUPLICATE KEY UPDATE message_number=message_number+1
Use INSERT...ON DUPLICATE KEY UPDATE. The MySQL manual has an example which does almost exactly what you need:
INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;
To make this work you need to add a UNIQUE index on the column that you use to check for duplicates. There is one important warning though:
In general, you should try to avoid using an ON DUPLICATE KEY clause on tables with multiple unique indexes.
Got a little confused by your question and your table structures but I think you want something like this.
INSERT INTO new_mail (username, message_number)
VALUES ($username, $message_number)
ON DUPLICATE KEY UPDATE message_number=message_number + 1;
This is presuming username is your primary key (more likely something like userid). Hope this helps.
EDIT: The ON DUPLICATE KEY UPDATE answers are better, but you could do this (eludes the select query):
Assuming you're using the mysqli extenson:
$db = //Some construction of mysqli object;
$sql = 'UPDATE tablename SET RowValue = RowValue + 1 WHERE message_number = ?';
$updateStatement = $db->prepare($sql);
$updateStatement->bind_param('i', $message_number);
$message_number = //Set message number;
$updateStatement->execute();
if ($updateStatement->affectedRows == 0) {
$sql = 'INSERT INTO tablename (RowValue, message_number) VALUES (?, ?)';
$insertStatement = $db->prepare($sql);
$insertStatement->bind_param('ii', $rowValue, $messageNumber);
$rowValue = something;
$messageNumber = something;
$insertStatement->execute();
}