gpt4 book ai didi

php - PDO while 循环重用输出模板

转载 作者:行者123 更新时间:2023-11-29 14:31:23 25 4
gpt4 key购买 nike

我尝试以这种方式使用 PDO 并重用输出模板:

 selected_products_show .= '<div class="'.$product_id.'">'.$product_name.'</div>'; 

用于自 $ordered=1 和 $shipped=1 起执行的两个查询。问题出在输出部分:

<?php if ($ordered == 1) { echo $selected_products_show;}?>
<?php if ($shipped == 1) { echo $selected_products_show;}?>

$selected_product_show 被第二个循环覆盖,其中 $shipped=1。如何提取正确的查询(现在发生)并附加正确的循环以及该循环的正确变量显示(全部使用一个 while 循环,同时重用相同的输出模板)?

这是代码:

$ordered = 1;
$shipped = 1;

if ($ordered == 1) {
$queryEnd = "WHERE product_id IN (?,?,?)";
}
if ($shipped == 1) {
$queryEnd = "ORDER BY product_id DESC LIMIT 5";
}

$query = "SELECT product_id, product_name FROM products $queryEnd";

if ($ordered == 1) {
$ordered_products = array(1,2,3);
$selected_products = $dbh->prepare($query);
$selected_products->execute($ordered_products);
}
if ($shipped == 1) {
$selected_products = $dbh->prepare($query);
$selected_products->execute();
}

while($row = $selected_products->fetch(PDO::FETCH_ASSOC)){
$product_id = $row["product_id"];
$product_name = $row["product_name"];
$selected_products_show .= '<div class="'.$product_id.'">'.$product_name.'</div>';
}

<?php if ($ordered == 1) { echo $selected_products_show;}?>
<?php if ($shipped == 1) { echo $selected_products_show;}?>

知道如何实现这一点吗?

最佳答案

function templating($selected_products){
$selected_products_show = '';
while($row = $selected_products->fetch(PDO::FETCH_ASSOC)){
$product_id = $row["product_id"];
$product_name = $row["product_name"];
$selected_products_show .= '<div class="'.$product_id.'">'.$product_name.'</div>';
}
return $selected_products_show;
}

$ordered = 1;
$shipped = 1;
$queryMAIN = "SELECT product_id, product_name FROM products";

if ($ordered == 1) {
$query = $queryMAIN." WHERE product_id IN (?,?,?)";
$ordered_products = array(1,2,3);
$selected_products = $dbh->prepare($query);
$selected_products->execute($ordered_products);
echo templating($selected_products);
}

if ($shipped == 1) {
$query= $queryMAIN." ORDER BY product_id DESC LIMIT 5";
$selected_products = $dbh->prepare($query);
$selected_products->execute();
echo templating($selected_products);
}

类似这样的吗?

关于php - PDO while 循环重用输出模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9967551/

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