在同一个查询中多次插入?

时间:2013-11-16 21:55:19

标签: php sql pdo

我该如何改进?这看起来很可怕。

$db->query("INSERT INTO items (player_id, sid, pid, itemtype, count, attributes) VALUES (".$db->lastInsertId().", 101, 1, 2460, 1, '')");
$db->query("INSERT INTO items (player_id, sid, pid, itemtype, count, attributes) VALUES (".$db->lastInsertId().", 102,3,1988,1,'')");
$db->query("INSERT INTO items (player_id, sid, pid, itemtype, count, attributes) VALUES (".$db->lastInsertId().", 103,4,2465,1,'')");
$db->query("INSERT INTO items (player_id, sid, pid, itemtype, count, attributes) VALUES (".$db->lastInsertId().", 104,5,2511,1,'')");
$db->query("INSERT INTO items (player_id, sid, pid, itemtype, count, attributes) VALUES (".$db->lastInsertId().", 105,6,2394,1,'')");
$db->query("INSERT INTO items (player_id, sid, pid, itemtype, count, attributes) VALUES (".$db->lastInsertId().", 106,7,2478,1,'')");
$db->query("INSERT INTO items (player_id, sid, pid, itemtype, count, attributes) VALUES (".$db->lastInsertId().", 107,8,2643,1,'')");
$db->query("INSERT INTO items (player_id, sid, pid, itemtype, count, attributes) VALUES (".$db->lastInsertId().", 108,10,2050,1,'')");
$db->query("INSERT INTO items (player_id, sid, pid, itemtype, count, attributes) VALUES (".$db->lastInsertId().", 109,102,2120,1,'')");
$db->query("INSERT INTO items (player_id, sid, pid, itemtype, count, attributes) VALUES (".$db->lastInsertId().", 110,102,2554,1,'')");

1 个答案:

答案 0 :(得分:4)

来自the manual

  

使用VALUES语法的INSERT语句可以插入多行。为此,请包含多个列值列表,每个列值都括在括号内并用逗号分隔。实施例

您还可以使用auto increment player_id列来实现此目的。

$db->query("INSERT INTO items (sid, pid, itemtype, count, attributes) 
VALUES (101, 1, 2460, 1, ''),
(102,3,1988,1,''),
(103,4,2465,1,'')");