0

我有一个从以下 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 (?,?,?);

消息和状态将保存在一个变量中

任何人都可以帮我解决这个问题吗?

4

2 回答 2

2

您可以在一个查询中完成所有操作。请参阅文档:INSERT ... SELECT 语法

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));
于 2012-07-17T13:04:47.223 回答
0
foreach( $result as $idValue ) {
    $sqlIns = "INSERT INTO messages (dID, message, status) VALUES ($idValue[0],?,?)";
}

这应该够了吧。虽然我不确定你为什么要使用fetchAll.

于 2012-07-17T13:06:01.733 回答