I have an array $feedArray
something like this
Array ( [0] => array('id'=>'3','val=>'Renta Comerciales'),
[1] => array('id'=>'4','val=>'Renta de Casas'),
[2] => array('id'=>'6','val=>'Venta de Casas '),
[3] => array('id'=>'7','val=>'Venta de Departamentos'),
[4] => array('id'=>'1','val=>'Venta de Terrenos') )
I have to make two query in a table called categoriasPlantilla
Then table has three columns
plantilla ,categoriaFeed, id
I have to check if the val
of the array exist in the categoriafeed
column of table then I have to update that id with the array id
if not then I have to insert a new row to the table
The value for plantilla is 11
I know how to do multiple insert in one query but how I can build such a query for update ?
To begin I was thinking of doing something like this
$sql = "INSERT INTO categoriaplantilla (plantilla,categoriafeed,id) values ";
$sqlUpdate = "UPDATE categoriaplantilla ";
foreach($feedArray as $key =>$val)
{
$sqlUpdate . =;
$sql . = ;
}
Please help me out
Thanks & Regards
You can't update rows set in one query. One row - one query. Also, you can use something like this
UPDATE table SET field1='aaa', field2='bbb' where id IN (1, 2,4).
But this query will set equal data to each row. Sometimes I use this one
INSERT INTO table(field1, field2) VALUES ('aaa', 'bbb')
ON DUPLICATE KEY
UPDATE SET field1='aaa', field2='bbb' where id IN (1, 2,4)
ps if you are use PK in your query, you may forgot about preformance almost in any case.
Most solutions used are based on checking primary keys, like INSERT INTO... ON DUPLICATE KEY
, or REPLACE INTO...
.
But, if you are checking non-primary keys which is column categoriaFeed
as you mentioned, I suggest you can create a mysql procedure to do that using mysql functions.
The basic code should be like this:
DROP PROCEDURE IF EXISTS func;
DELIMITER //
CREATE PROCEDURE func()
BEGIN
IF '123' in ('Renta Comerciales', 'Renta de Casas', 'Venta de Casas') THEN
UPDATE `may` SET `fone` = 'aaaaa' WHERE `id` = 1;
ELSE
INSERT INTO `may` VALUES ('1','2','3');
END IF;
END//
DELIMITER ;
CALL func();
The 123
equals to your val
, you can check if it's in your given array. Then you can just update or insert data by the if-statement
.
This is probably an useful way to solve your problem. I'm in GMT+8
time zone and I'm gonna sleep now, it's 23:00PM. I'll check your replies tomorrow to see what I can help then.
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.