gpt4 book ai didi

php - PDO 数组从 MySQL 查询到插入查询

转载 作者:行者123 更新时间:2023-11-29 08:49:59 25 4
gpt4 key购买 nike

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

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

谁能帮我解决这个问题吗?

最佳答案

您可以在一个查询中完成这一切。请参阅文档: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));

关于php - PDO 数组从 MySQL 查询到插入查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11523069/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com