Forum Moderators: coopster

Message Too Old, No Replies

Smarty and nested loop

         

IteQ

12:57 pm on Feb 8, 2008 (gmt 0)

10+ Year Member



Hello,

i have two DB tables:

users table:
+----+-------+----------------+
¦ id ¦ name ¦ mail ¦
+----+-------+----------------+
¦ 1 ¦ user1 ¦ test@test.com ¦
¦ 2 ¦ user2 ¦ test2@test.com ¦
+----+-------+----------------+

messages table:
+----+-----+-----------------------+
¦ id ¦ uID ¦ title ¦
+----+-----+-----------------------+
¦ 1 ¦ 1 ¦ Lorem ipsum dolor ¦
¦ 2 ¦ 1 ¦ Vestibulum ante ipsum ¦
¦ 3 ¦ 2 ¦ Morbi egestas ¦
+----+-----+-----------------------+

uID - user id number from users table.

Ok, i want make this table with Smarty template engine: containing username and message title

PHP code:
$messagesSql = mysql_query("SELECT `title`, `uID` FROM `messages`");
while ($get_messages = mysql_fetch_array($messagesSql)) {
$messages[] = $get_messages;

$usersSql = mysql_query("SELECT `name` FROM `users` WHERE id='$get_messages[uID]'");
$users = mysql_fetch_array($usersSql);
$messages[] = $users;
}
$smarty->assign('messages', $messages);

HTML code:
<table width="50%" border="1">
{foreach item=m from=$messages}
<tr>
<td>{$m.name}</td>
<td>{$m.title}</td>
</tr>
{/foreach}
</table>

But smarty ouptut this table:
<table width="50%" border="1">
<tr>
<td></td>
<td>Lorem ipsum dolor</td>
</tr>
<tr>
<td>user1</td>
<td></td>
</tr>
<tr>
<td></td>
<td>Vestibulum ante ipsum</td>
</tr>
<tr>

<td>user1</td>
<td></td>
</tr>
<tr>
<td></td>
<td>Morbi egestas</td>
</tr>
<tr>
<td>user2</td>
<td></td>
</tr>
</table>

How i can make this table this situation?

<table width="50%" border="1">
<tr>
<td>user1</td>
<td>Lorem ipsum dolor</td>
</tr>
<tr>
<td>user1</td>
<td>Vestibulum ante ipsum</td>
</tr>
<tr>
<td>user2</td>
<td>Morbi egestas</td>

</tr>
</table>

[edited by: jatar_k at 1:13 pm (utc) on Feb. 8, 2008]
[edit reason] removed urls and added code [/edit]

cameraman

6:51 pm on Feb 8, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Welcome to WebmasterWorld, IteQ!

The way you're pulling your data from the two tables into one array makes it difficult to work with. Comment out all the smarty stuff and right after your while loop, add:

print_r($messages);

and you'll see what I mean.
There's several different ways to do it. If you want to do two separate queries to keep the sql simple, I suggest using the message id as the index for $messages. Then you can add the user's name to the correct array element instead of creating a new array element.

Alternatively you could combine the two queries into one:
SELECT title, uID, name FROM messages,users WHERE users.id=uID

Keep the smarty stuff commented out and just print/echo/dump your "raw" data until you get that part worked out, then work with adding smarty afterward.