Reputation: 35
I need to update the information of a mysql table database from a php array.
I'm looking for the best approach to do this, what I want to do is to update an existing database table with new information, this means that there could be new rows, the existing rows could have new values in their fields, or rows deleted.
The approaches that I am thinking are:
What do you think? Some ideas for the better approach? Thanks for your support.
Upvotes: 1
Views: 605
Reputation: 63
The DBMS can do this for you. Just use the command:
'INSERT INTO table ({target list}) VALUES({values}) ON DUPLICATE KEY UPDATE val1={value} , val2={value},...'
Upvotes: 1
Reputation: 42093
You can use INSERT ... ON DUPLICATE KEY UPDATE to INSERT
new rows and UPDATE
existing rows.
Example:
INSERT INTO t1 (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE a=1,b=2,c=3;
You have to build DELETE
statement using some trick in php.
Example:
<?php
$data = array(
array( 'a'=>1, 'b'=>2, 'c'=>3 ),
array( 'a'=>4, 'b'=>5, 'c'=>6 ),
array( 'a'=>7, 'b'=>8, 'c'=>9 ),
);
$condition = implode( ',', array_map( function($temp){return sprintf("('%s','%s','%s')",$temp['a'],$temp['b'],$temp['c']);},$data));
$sql = "DELETE FROM t1 WHERE (a,b,c) NOT IN (" . $condition . ");";
echo $sql; // DELETE FROM t1 WHERE (a,b,c) NOT IN (('1','2','3'),('4','5','6'),('7','8','9'));
// OR
$condition1 = implode( ',', array_map( function($temp){return sprintf("'%s'",$temp['a']);},$data));
$sql1 = "DELETE FROM t1 WHERE a NOT IN (" . $condition1 . ");";
echo $sql1; // DELETE FROM t1 WHERE a NOT IN ('1','4','7');
?>
Upvotes: 1