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

php query called in tpl using Smarty

我是 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'] .'<br />';
    }

//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' 目录中看起来如何吗?

提前致谢

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

index.php

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

index.tpl

// head, 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

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

让这个工作,这就是我所做的。

在我的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'] }<br />

  {/foreach}
 </p>

就像我说的,我在这方面完全是菜鸟,但还是展示了它。谢谢@Tobias .F