gpt4 book ai didi

php - 如何将 MySQL 行拆分为连接中每个表的单独变量

转载 作者:行者123 更新时间:2023-11-29 20:21:16 25 4
gpt4 key购买 nike

如果我从 JOIN 查询中获取结果,如何为每行连接中的每个表获取单独的变量?

例如:

$result = $mysql->query(sprintf('SELECT *
FROM `TableOne` one
JOIN `TableTwo` two ON (one.TwoID = two.TwoID)
JOIN `TableThree` three ON (one.ThreeID = three.ThreeID)
WHERE one.OneID = %u',
(int)$primary_key));
while ($row = $result->fetch_assoc()) {
// Instead of $row, I want:
// $one: all fields from TableOne
// $other: all fields from TableTwo and TableThree
}

最佳答案

解决方案:

function mysqli_fetch_assoc_per_table(mysqli_result $result, $instruction) {
$row = $result->fetch_assoc();
if (!$row) return false;
$fields = $result->fetch_fields();

$groups = array();
foreach (explode(',', $instruction) as $arg) {

$group = array();
foreach (explode('|', $arg) as $table) {
foreach ($fields as $field) {
if ($field->table == $table) {
$group[$field->name] = $row[$field->name];
}
}
}

$groups[] = $group;
}

return $groups;
}

用法:

while (list($one, $other) = mysqli_fetch_assoc_per_table($result, 'one,two|three')) {

}

关于php - 如何将 MySQL 行拆分为连接中每个表的单独变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39503617/

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