首页 文章

使用Smarty在tpl中调用的php查询

提问于
浏览
0

我n00b,所以基本上我想使用smarty从我的.tpl文件中调用我的index.php文件中的查询:

Index.php

<?php

//Database connection
$db = mysqli_connect('xx','xx','','xx')
or die('Error connecting to MySQL server.');

//access Smarty template engine
require_once('Smarty-3.1.30/libs/Smarty.class.php');

$smarty = new Smarty();
$smarty->template_dir = 'views';
$smarty->compile_dir = 'tmp';


//query product page
$query = "SELECT * FROM cs_shop";
mysqli_query($db, $query) or die('Error querying database.');

$result = mysqli_query($db, $query);
$row = mysqli_fetch_array($result);


//query
while ($row = mysqli_fetch_array($result)) {
$row['product_category'] . ' ' . $row['product_price'] . ': ' . 
$row['product_quantity'] . ' ' . $row['product_about'] .' ' 
.$row['product_color'] .'
'; } //db collect data $smarty->assign('row', $row); //template $smarty->display('index.tpl'); mysqli_close($db); ?>

我在index.php中使用的while循环是我想在我的.tpl文件中调用的,我是smarty的新手,无法让它工作,测试数据库连接并且它工作,我的,Smarty被称为无错误 .

它是一个基本的静态页面,我只是在做实验,使用Smarty,所以我只想显示查询列表没有td或类似的东西 .

那么有人可以给我一个例子,如果我想显示查询,我的.tpl文件将如何位于我的'views'目录中?

提前致谢

2 回答

  • 0

    有了这个工作,这就是我做的 .

    在我的 index.php 中(仅显示我所知道的不正确且现在正确)

    <?php
    $new = ['product_category','product_price','product_quantity','product_about','product_color'];
    
    //added an array - rows
    $rows = array();
    
    //while loop calling array adding products columns to it
    while ($row = mysqli_fetch_array($result)) {
     $rows[] = array(
        'product_category' => $row['product_category'],
        'product_price' => $row['product_price'],
        'product_quantity' => $row['product_quantity'],
        'product_about' => $row['product_about'],
        'product_color' => $row['product_color']
    );
    }
    
    //db collect data - calls rows
    $smarty->assign('row', $rows); 
    //template
    $smarty->display('index.tpl');
    

    index.tpl

    <p>
      {foreach from=$row item="item"} 
    
         {$item['product_category'] }
    {/foreach} </p>

    就像我说的那样,我完全是noob,但得到它显示 . 谢谢@Tobias .F

  • 1

    一个简短的示例如何在 <p> 标记中显示数组中的几个单词作为选项:

    index.php

    $rows = ['hello', 'there', 'this', 'is', 'me'];
    $smarty->assign('rows', $rows);
    $smarty->display('index.tpl');
    

    index.tpl

    //头,css等,这里没关系

    <p>
      {foreach from=$rows item="item"}
        {$item}<br>
      {/foreach}
    </p>
    

    这将产生一些评估为:

    <p>
      hello<br>
      there<br>
      this<br>
      is<br>
      me<br>
    </p>
    

    并作为解释HTML:

    hello
    there
    this
    is
    me
    

    作为变量的内容,您可以(几乎)传递任何您想要的内容 .

相关问题