putting data from multiple tables into an array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
whypie
Forum Newbie
Posts: 2
Joined: Wed Sep 02, 2009 3:54 am

putting data from multiple tables into an array

Post by whypie »

i am trying to get data from two tables and put them into an array that i can return to my template. - i should mention that im quite new to php.

here are my tables:

horses:

id, name, owner_id

owners:

id, name

i have a function called get_horses() that returns details on all of the horses, but i want it to also get the owner name and put that into the array, how can i do this?

Code: Select all

class horse_details {
    
    function get_horses(){
        $query = "SELECT * FROM horses";
        $result = mysql_query($query);
 
        $horses = array();
 
        while($tmp = mysql_fetch_assoc($result)) {
            $horses[] = $tmp;
        }
 
        return $horses;
    }
 
}
my smarty template:

Code: Select all

{foreach item=horse from=$horses}
<tr>
    <td>{$horse.name}</td>
    <td>{$horse.breed}</td>
    <td><a href="owners.php?action=view&owner_id={$horse.owner_id}">{$i.want.the.owner.name.here}</a></td>
</tr>
{foreachelse}
<tr>
    <td colspan="3">No items were found</td>
</tr>
{/foreach}
any help would be great. - please let me know if you need any of the other code.
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: putting data from multiple tables into an array

Post by Benjamin »

:arrow: Moved to PHP - Code
Mark Baker
Forum Regular
Posts: 710
Joined: Thu Oct 30, 2008 6:24 pm

Re: putting data from multiple tables into an array

Post by Mark Baker »

Assuming that every horse has an owner

Code: Select all

 
SELECT H.*,
       O.name AS ownerName
  FROM horses H,
       owners O
 WHERE O.id = H.owner_id
 
whypie
Forum Newbie
Posts: 2
Joined: Wed Sep 02, 2009 3:54 am

Re: putting data from multiple tables into an array

Post by whypie »

excellent. the join worked. thanks. :lol:
Post Reply