Php 在Smarty中返回数据库值

Php 在Smarty中返回数据库值,php,smarty,Php,Smarty,我有这个Smarty代码来获取数据: $sel=mysql_query("select id, name from form"); $smarty->assign('contact', mysql_fetch_row($sel)); $smarty->display('testfunction.tpl'); 我的模板文件: <ul> {foreach from=$contact item=foo} <li>{$foo}</li&

我有这个Smarty代码来获取数据:

$sel=mysql_query("select id, name from form");
$smarty->assign('contact', mysql_fetch_row($sel));
$smarty->display('testfunction.tpl');
我的模板文件:

<ul>
    {foreach from=$contact item=foo}
        <li>{$foo}</li>
    {/foreach}
</ul>
但我希望输出像:

1:a
2:b
如果您使用,它完全按照它所说的去做——它获取一行,但不超过一行。我猜你的结果集是这样的(如果我错了,请在你的问题中澄清):

解决这一问题的一种方法是构建一个阵列,然后可以使用Smarty将其分解,如下所示:

/* PHP code */
$your_array = array();

$sel=mysql_query("select id, name from form");
while($row=mysql_fetch_array($sel)) {
   $your_array[] = $row;
}

$smarty->assign('contact', $your_array);
$smarty->display('testfunction.tpl');
[1] => (
     [0] => 1, 
     [1] => a
),

[2] => (
     [0] => 2, 
     [1] => b
)
现在Smarty中有一个数组,基本上如下所示:

/* PHP code */
$your_array = array();

$sel=mysql_query("select id, name from form");
while($row=mysql_fetch_array($sel)) {
   $your_array[] = $row;
}

$smarty->assign('contact', $your_array);
$smarty->display('testfunction.tpl');
[1] => (
     [0] => 1, 
     [1] => a
),

[2] => (
     [0] => 2, 
     [1] => b
)
这可以像您描述的那样显示:

{* Smarty Code *}
<ul>
    {foreach from=$contact item=foo}
        <li>{$foo[0]}: {$foo[1]}</li>
    {/foreach}
</ul>
{*Smarty code*}
    {foreach from=$contact item=foo}
  • {$foo[0]}:{$foo[1]}
  • {/foreach}
我还没试过,但它应该可以。如果不正确,请在模板中使用
{debug}
查看数组
$contact
是如何形成的

另一条建议:

您在这里使用的PHPs mysql连接器已被弃用。非常不鼓励使用此扩展。相反,应该使用or扩展名