2014-11-16 52 views
0

我不知道如何通过使用PDO更新或插入多行。请帮帮我。(PDO PHP)更新或插入多行的最快方法?

的东西是在我心目中是:

$stmt = $dbh->query("update_line_1; update_line_2; update_line_3"); 
//update_line_1: update table a set a.column1 = "s1" where a.id = 1 
//update_line_2: update table a set a.column1 = "s2" where a.id = 2 
//.... 

$stm = $dbh->query("insert_line_1; insert_line_3; insert_line_3"); 
//something is like the update line above. 

我不知道这样的工作与否。如果您有其他方法,请告诉我。非常感谢你。

如果我使用准备语句,我只是每次更新每一行。 (这比上述更安全)

$stmt = $dbh->prepare("update table a set a.colum1 = :column1 where a.id = :id"); 
$stmt->bindParam(":column1","s1"); 
$stmt->bindparam(":id",1); 
$stmt->execute(); 

最讨厌的事情,我不想使用循环来经过数组中的所有元素,并更新或每次插入每个元素

是群集安全更新或插入多行到数据库的另一种方法?感谢您的帮助。

对不起,我的英语。

回答

5

对于插入,你可以插入多行值得的语法如下数据:

INSERT INTO table (col1, col2, col3) 
VALUES 
    ('1', '2', '3'), 
    ('a', 'b', 'c'), 
    ('foo', 'bar', 'baz') 

对于更新,该更新将默认效果多的行符合查询条件。因此,像这样将更新整个表

UPDATE table SET col = 'a' 

如果你想为每个行更新不同的值,你真的没有太多其他的,而不是做每个操作查询的一个选择。不过我建议,建立在你的PDO例如,你可以做这样的事情:

$update_array = array(
    1 => 'foo', 
    2 => 'bar', 
    10 => 'baz' 
); // key is row id, value is value to be updated 

$stmt = $dbh->prepare("UPDATE table SET column1 = :column1 where id = :id"); 
$stmt->bindParam(":column1",$column_value); 
$stmt->bindparam(":id",$id); 
foreach($update_array as $k => $v) { 
    $id = $k 
    $column_value = $v; 
    $stmt->execute(); 
    // add error handling here 
} 

通过这种方法你至少撬动使用事先准备好的声明,以尽量减少查询的开销。

+0

希望有个更好的答案。 – user3883314

+0

@ user3883314你希望做什么更好?没有办法大规模更新您尝试使用不同WHERE条件定位的多行。该功能根本不存在。 –

+0

@ user3883314这是一个很好的答案... –