Write a function to get all records from table

Discussion in 'PHP' started by rasana, Nov 6, 2008.

  1. #1
    Hi All,

    I'm working on a project where I have to write a function to get all records from a table which will return array of objects.
    I've written a function to get a single record from table and working fine..but to get all records i'll have to write while loop..how would I store data in array and how would I display all data...?

    Below is function to get a single record

    $sql = "select * from student where id = 1";
    $getData = $db->getRecord($sql);
    
    function getRecord($sql)
        {
            $result = mysql_query($sql) or die(mysql_error());
            $data_set = mysql_fetch_array($result);
                
        return $data_set;
        } 
    PHP:
     
    rasana, Nov 6, 2008 IP
  2. xlcho

    xlcho Guest

    Messages:
    532
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    0
    #2
    The simplest way to display the data returned from a DB is something like this:
    $result = mysql_query($query);
    while($row = mysql_fetch_assoc($result))
    {
       //you can display the information here using echo, printf or a similar function. 
       //You'll have every row returned from the DB in the array $row. 
       echo $row[...'];
    }
    Code (markup):
    Lets say you have the table 'users' which has three columns - id, name, age. You can show all the users with the fallowing:
    $result = mysql_query("SELECT * FROM users");
    while($row = mysql_fetch_assoc($result))
    {
       printf("%s. %s is %s years old<br />", $row['id'], $row['name'], $row['age']);
    }
    Code (markup):
    The information will be displayed like that:
    or something similar..
     
    xlcho, Nov 6, 2008 IP
  3. rasana

    rasana Peon

    Messages:
    8
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks a lot xlcho!!!
     
    rasana, Nov 6, 2008 IP