gpt4 book ai didi

php - 从具有公共(public)变量的多个表中选择不同的列

转载 作者:行者123 更新时间:2023-11-29 01:34:41 25 4
gpt4 key购买 nike

我有三个表: - food - toys - animals

每个表都有列 - idcoloritem

toys 有额外的列 - sndate 等等

需要从color = red所有 表中选择所有 项,并在客户端分别获取它们

类似于:

$color = 'red';
$sql = "select * from food, toys, animals where color = :acolor";
$st = $db->prepare($sql);
$st->execute([":acolor" => $color]);
$food = $toys = $animals = '';
while($row = $st->fetch()){
$food .= "<div class='food' data-id = " . $row['food.id'] . ">" . $row['food.item'] . "</div>\n";
$toys .= "<div class='toys' data-id = " . $row['toys.id'] . " data-serial = " . $row['toys.sn'] . " data-date = '" . $row['toys.date'] . "'>" . $row['toys.item'] . "</div>\n";
}
$animals .= "<div class='animals' data-id = " . $row['animals.id'] . ">" . $row['animals.item'] . "</div>\n";
}
$arr = [];
array_push($arr, $food, $toys, $animals);
echo json_encode($arr);

客户端

...
data = JSON.parse(data);
$('#wrapfood').html(data[0]);
$('#wraptoys').html(data[1]);
$('#wrapanimals').html(data[2]);

作为最终结果:

wrapfood 应该有 5 个类为 food
的 divwraptoys 应该有 9 个 div 类 toys
wrapanimals 应该有 21 个类为 animals

的 div

我尝试了上述代码的各种版本但没有成功 - 在服务器端出现错误。

有什么帮助吗?

最佳答案

你可以用这个

$data = array('food' => array(),'toys' => array(),'animals' => array());
$color = 'red';
$foodSql = "select * from food where color = :acolor";
$toySql = "select * from toys where color = :acolor";
$animalSql = "select * from animals where color = :acolor";
$ft = $db->prepare($foodSql);
$tt = $db->prepare($toySql);
$at = $db->prepare($animalSql);
$ft->execute([":acolor" => $color]);
$tt->execute([":acolor" => $color]);
$at->execute([":acolor" => $color]);
$food, $toys, $animals = '';
while($row = $ft->fetch()){
$food .= "<div class='food' data-id = " . $row['food.id'] . ">" . $row['food.item'] . "</div>\n";
}
array_push($data['food'], $food);

while($row = $tt->fetch()){
$toys .= "<div class='toys' data-id = " . $row['toys.id'] . " data-serial = " . $row['toys.sn'] . " data-date = '" . $row['toys.date'] . "'>" . $row['toys.item'] . "</div>\n";
}
array_push($data['toys'],$toys);

while($row = $at->fetch()){
$animals .= "<div class='animals' data-id = " . $row['animals.id'] . ">" . $row['animals.item'] . "</div>\n";
}
array_push($data['animals'],$animals);
echo json_encode($data);

然后在客户端你可以访问数据

data = JSON.parse(data);
$('#wrapfood').html(data.food);
$('#wraptoys').html(data.toys);
$('#wrapanimals').html(data.animals);

关于php - 从具有公共(public)变量的多个表中选择不同的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57387646/

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