我有一个数组,我从以下PDO获得:
$sqlQry = "SELECT Devices.dID FROM Friends LEFT OUTER JOIN Devices ON Friends.fID = Devices.dUID WHERE Devices.dID IS NOT NULL GROUP BY Devices.dID";
$db = getConnection();
$sth = $db->prepare($sqlQry);
$sth->execute();
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
print_r($result);
数组返回:
Array ( [0] => Array ([dID] => 2[0] => 2 ) [1] => Array ( [dID] => 3 [0] => 3 ))
对于每个dID值,我需要运行一个插入查询,该查询接受dID并将其插入到具有外部值的同一数据库中的表中。
$sqlIns = "INSERT INTO messages (dID, message, status") VALUES (?,?,?);
消息和状态将保存在变量
中任何人都可以帮我解决这个问题吗?
答案 0 :(得分:2)
您可以在一个查询中执行此操作。请参阅文档:INSERT ... SELECT Syntax
INSERT into messages (dID, message, status)
SELECT Devices.dID, ?, ?
FROM Friends
LEFT OUTER JOIN Devices ON Friends.fID = Devices.dUID
WHERE Devices.dID IS NOT NULL
GROUP BY Devices.dID
PDO看起来像这样:
// database connection
$conn = new PDO(...);
// new data
$message = 'xxx';
$status = 'yyy';
// query
$sql = "INSERT into messages (dID, message, status)
SELECT Devices.dID, ?, ?
FROM Friends
LEFT OUTER JOIN Devices ON Friends.fID = Devices.dUID
WHERE Devices.dID IS NOT NULL
GROUP BY Devices.dID";
$q = $conn->prepare($sql);
$q->execute(array($message,$status));
答案 1 :(得分:0)
foreach( $result as $idValue ) {
$sqlIns = "INSERT INTO messages (dID, message, status) VALUES ($idValue[0],?,?)";
}
这应该可以解决问题。虽然我不确定您为什么使用fetchAll
。