如何将php while循环分配给smarty以获得所需的结果

时间:2014-05-20 11:57:47

标签: php mysql smarty

我想在滑块问题中展示精选广告是否有两张桌子必须用于获取广告。第一个是class_ads,它包含标题,描述,价格等广告的所有信息,第二个表格是class_ads_pictures,我必须匹配每个广告的ID,并从表格中获取文件夹和图片名称....

请检查我糟糕的逻辑并教我

  <?php

    require_once "include/include.php";

    global $db;
    global $lng;
    $smarty = new Smarty;
    $smarty = common($smarty);


    $featured_ads = mysql_query("SELECT * FROM class_ads where active=1 and featured=1 limit 50"); 
    while ($tmp = mysql_fetch_array($featured_ads)) { 
        $ad_id      = $temp['id'];
        $ad_title   = $temp['title'];

        //check for image if featured ad have image (Need to fetch only single image)
        $featured_ads_images = mysql_query("select from class_ads_pictures where ad_id=$ad_id order by order_no"); 
        $img = mysql_fetch_array($featured_ads_images);
        $img_id         = $img['id'];
        $ad_img         = $img['picture'];
        $img_folder     = $img['folder'];


        // Problem is how to assign and what have to assign, to get display in html file ...
    } 

    $smarty->assign('what', $what);

    $db->close();
    if($db->error!='') { $db_error = $db->getError(); $smarty->assign('db_error',$db_error); }

    $smarty->display('header_featured.html');
    close();
    ?>

1 个答案:

答案 0 :(得分:0)

下面的代码应该可行。但是你不应该使用mysql而是使用PDO或mysqli,因为不推荐使用mysql。

<?php

require_once "include/include.php";

global $db;
global $lng;
$smarty = new Smarty;
$smarty = common($smarty);


$ads = array();

$featured_ads = mysql_query("SELECT * FROM class_ads where active=1 and featured=1 limit 50"); 
while ($temp = mysql_fetch_assoc($featured_ads)) { 
    $record = array();
    $record['ad_id']      = $temp['id'];
    $record['ad_title']   = $temp['title'];

    //check for image if featured ad have image (Need to fetch only single image)
    $featured_ads_images = mysql_query("select * from class_ads_pictures where ad_id={$record['ad_id']} order by order_no"); 
    $img = mysql_fetch_assoc($featured_ads_images);
    $record['img_id']         = $img['id'];
    $record['ad_img']         = $img['picture'];
    $record['img_folder']     = $img['folder'];

    $ads[] = $record;
} 

$smarty->assign('ads', $ads);

$db->close();
if($db->error!='') { $db_error = $db->getError(); $smarty->assign('db_error',$db_error); }

$smarty->display('header_featured.html');
close();
?>

在Smarty中你可以简单地使用它:

 {foreach item=item  from=$ads} 
  {$item.ad_id}
  {$item.ad_title}
  {$item.img_id}
  {$item.ad_img}
  {$item.img_folder}
 {/foreach}