Reputation: 23
I have this Smarty code to fetch data:
$sel=mysql_query("select id, name from form");
$smarty->assign('contact', mysql_fetch_row($sel));
$smarty->display('testfunction.tpl');
My template file:
<ul>
{foreach from=$contact item=foo}
<li>{$foo}</li>
{/foreach}
</ul>
This outputs:
1
a
But I want the output to be like:
1:a
2:b
Upvotes: 0
Views: 1217
Reputation: 16304
If you use mysql_fetch_row
, it does exactly what it says - it fetches a row, but not more than one. My guess is your result set looks like this (if I'm mistaken, please clarify in your question):
id | name
----+------------
1 | a
2 | b
A way of getting around this is to build up an array which you then can take apart with Smarty, something like this:
/* 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');
You now have an array in Smarty which basically looks like this:
[1] => (
[0] => 1,
[1] => a
),
[2] => (
[0] => 2,
[1] => b
)
This can be displayed like you described it:
{* Smarty Code *}
<ul>
{foreach from=$contact item=foo}
<li>{$foo[0]}: {$foo[1]}</li>
{/foreach}
</ul>
I haven't tried it, but it should do the job. If it doesn't properly, use a {debug}
in your template to see how the array $contact
is formed.
Another word of advice:
PHPs mysql connector, which you're using here, is deprecated. Use of this extension is highly discouraged. Instead, the MySQLi or PDO_MySQL extension should be used.
Upvotes: 1