insert or replace id exists or is difrent - php

I have this code in php to insert into database
$sqlx="INSERT INTO bruno_wallet (foto, data, nome, evento,horarios,obs,horas,valorhora,totalparcial,props,id_do_mes,nome_id )
VALUES ('$ii', '$data','$nome[0]','$evento' ,'$horarios','$obs','$numeros_horas','$valor_horas','$total_parcial','$props',' $id_postt','$nomeid') " ;
but it always inserts news values.
I want to : insert if its new and replace if old values if it exists

You shouldn't be using the INSERT command then. First find if it already is in your database then insert or leave it as it is.

You can use DUPLICATE KEY UPDATE if you have only primary key in table.
Note than: if you have any other key like Unique Key etc than it will not work.
$sqlx="INSERT INTO bruno_wallet (foto, data, nome, evento,horarios,obs,horas,
valorhora,totalparcial,props,id_do_mes,nome_id )
VALUES ('$ii', '$data','$nome[0]','$evento' ,'$horarios','$obs',
'$numeros_horas','$valor_horas','$total_parcial','$props','$id_postt','$nomeid')
ON DUPLICATE KEY UPDATE
foto = '$ii', data = '$data', nome = '$nome[0]', evento = '$evento', horarios = '$horarios',
obs = '$obs', horas = '$numeros_horas', valorhora = '$valor_horas',
totalparcial = '$total_parcial', props = '$props', id_do_mes = '$id_postt', nome_id = '$nomeid'
";
Explanation:
From dev.mysql.com: You can use the VALUES(col_name) function in the
UPDATE clause to refer to column values from the INSERT portion of the
INSERT ... ON DUPLICATE KEY UPDATE
If foto is a primary key than after ist insertion every time this query will update the record.

Hi here is simple and easy solution try it.
$result = mysql_query("SELECT * FROM bruno_wallet WHERE foto = '$ii' "); //in where condition add whatever condition you want
if( mysql_num_rows($result) > 0) {
$sqlx = "UPDATE bruno_wallet SET foto ='$ii', data = '$data', nome = '$nome[0]', evento = '$evento' ,horarios = '$horarios',obs = '$obs',horas = '$numeros_horas',valorhora = '$valor_horas',totalparcial = '$total_parcial',props = '$props',id_do_mes = ' $id_postt',nome_id = '$nomeid' WHERE foto = '$ii' "; //in where condition add whatever condition you want
}
else
{
$sqlx="INSERT INTO bruno_wallet (foto, data, nome, evento,horarios,obs,horas,valorhora,totalparcial,props,id_do_mes,nome_id )
VALUES ('$ii', '$data','$nome[0]','$evento' ,'$horarios','$obs','$numeros_horas','$valor_horas','$total_parcial','$props',' $id_postt','$nomeid') " ;
}

You cannot do that this way, an INSERT command is always an additional row in your database. You can however do something with subqueries, But the better practice is to do this in code.
You should run SELECT using the columns and values you have, If exists run a insert else run a update.
The problem you present is impossible to solve, since the database will not have anything to update if all columns match, I hope you understand how that would work, and that the way you intend it is not logical. Also you are not mentioning what your "matchcolumns" are. so if what matches what it should be an update...
If you do need to proceed this way, Please provide us more information so we can assist

If you are using MYSQL you can use INSERT ... ON DUPLICATE KEY UPDATE from Mysql manual
When doing an insert where a unique key is present the existing record will be updated with the fields you specify.

The easiest way to solve this is to check if the data sent exists in the database already. If the data is already in the database run an update query and run insert if not.
Run this first
Select * from bruno_wallet where nome_id='$nomeid';
Now fetch the data and set if to any variable. For this purpose am going to call it $info
Now run
if(!$info)
{
"INSERT INTO bruno_wallet (foto, data, nome, evento,horarios,obs,horas,valorhora,totalparcial,props,id_do_mes,nome_id )
VALUES ('$ii', '$data','$nome[0]','$evento' ,'$horarios','$obs','$numeros_horas','$valor_horas','$total_parcial','$props',' $id_postt','$nomeid') " ;
}else{
Run update query
}
`

Related

How can I insert or update records from different tables

I have two tables: parts (with codice, pezzi, durata) and magazzino (with codiceM, pezziM, durataM)
I want to add or update some records from parts to magazzino. What I would Like to do is:
check if codice is already present in the table magazzino, if not INSERT a record with codice, pezzi and durata.
if codice is already present in magazzino, sum and UPDATE pezzi and durata associated with codice.
I use phprunner to create database and insert a button that executes the code after selecting a record in parts.
Here is my code that execute with no errors but it gaves me no results.
$record = $button->getNextSelectedRecord();
$cod=$record["codice"]; //variable assignments
$qnty=$record["pezzi"];
$time=$record["durata"];
$control=0; //control variable
$con = new mysqli("localhost","root","","provaMagazzino") or die("sorry not connected");
$sql = "SELECT * FROM magazzino";
$resultq = $con->query($sql);
while($row = mysql_fetch_array($resultq)){ // check and update records in magazzino table
echo($row['codice']);
if ($row['codice']==$cod) {
$row['pezziM']+=$qnty;
$row['durataM']+=$time;
echo('durataM');
$control=1;
break;
}
}
if ($control=0) { //add new records al Magazzino if control variable is zero
$resultq->codiceM = $record["codice"];
$resultq->durataM = $record["durata"];
$resultq->pezziM = $record["pezzi"];
$resultq->descrizioneM = $record["descrizione"];
$resultq->Add();
}
You can calculate your data with mysql only
SELECT p.codice, IFNULL(p.pezzi, 0) + IFNULL(m.pezziM,0) AS updatedPezzi,IFNULL(p.durata,0) + IFNULL(m.durataM,0) AS updatedDurata FROM parts AS p
left join magazzino m on p.codice = m.codiceM
IFNULL is added just to be sure that your data will not be lost if the record does not exist in magazzino table.
The result will be data that need to be inserted into magazzino table and you can customize it with WHERE condition to calculate specific rows
After that you can insert this data from php to mysql again if INSERT ON DUPLICATE is not good for you.
There are a lot of cases. As I see the codice column should be unique so for me insert on duplicate key update is the best choice here
Is this correct?
$record = $button->getNextSelectedRecord();
$cod=$record["codice"]; //variable assignments
$qnty=$record["pezzi"];
$time=$record["durata"];
INSERT INTO magazzino(codiceM, pezziM, durataM)
VALUES ('$cod', '$qnty', '$time')
ON DUPLICATE KEY UPDATE
codiceM= values($cod)
pezziM= pezziM+ values($qnty)
durataM= durataM+ values($time)

INSERT ...ON DUPLICATE KEY UPDATE when key is not always known?

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)

PHP Insert or update table

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!
:)

Check if exists, if so, update by 1++, if not 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();
}

A php function to insert or update mysql table on true/false

Im trying to write a function to check whether a user exists in a table, if so, update the row, if not, insert it.
Here is my function:
function UserExists($screenname){
$mysql = mysql_fetch_array ( mysql_query("SELECT * FROM `users` WHERE `screenname` = '$screenname' "));
if($mysql){
return TRUE;
}else{
return FALSE;
}
}
And im executing this function using the following:
if(UserExists($user)){
mysql_query("UPDATE `users` SET `token` = '$token' , `secret` = '$secret' WHERE `screenname` = '$user' ");
}else{
mysql_query("INSERT INTO `users` (`screenname`, `token`, `secret`) VALUES ('$user', '$token', '$secret')");
}
Its not doing anything, not throwing any errors, but also not updating the table.
You'd want to take a look at the INSERT ... ON DUPLICATE KEY UPDATE ... MySQL query syntax to make this work with just one query.
INSERT INTO users (screenname, token, secret) VALUES ('screenname', 'token', 'secret')
ON DUPLICATE KEY UPDATE token = 'token', secret = 'secret'
screenname should be unique (or a primary key) which you probably don't have at the moment. I suggest to add an ID column in your database table and use that to refer to database rows.
Your best solution is ON DUPLICATE KEY as JoostK stated
Call mysql_error after the calls to see what error you are getting. Also another good debugging technique is to execute it on the server using a MySQL client such as mysqlfront or phpMyAdmin.
I'd simply suggest to use REPLACE INTO SET col = val in this case, all you need to do is define a unique index on the table.
The Replace Command will have a look at the unique indexes, if a row already exists it will update the existing, if not it will insert a new one.

Categories