PDO while循环重用输出模板

时间:2012-04-01 19:29:02

标签: php mysql arrays pdo while-loop

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

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

要用于两个查询,因为$ ordered = 1&amp; $运= 1。 问题出在输出部分:

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

$ selected_product_show被$ shipped = 1的第二个循环覆盖。如何提取正确的查询(现在发生)并使用正确的变量显示附加正确的循环(All with while 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;}?>

知道如何实现这一目标吗?

1 个答案:

答案 0 :(得分:1)

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);
}

这样的东西?