Results 1 to 3 of 3

Thread: [RESOLVED]Write function to get all records?

  1. #1

    Thread Starter
    Lively Member rasana's Avatar
    Join Date
    Jan 2007
    Location
    Mumbai, (India)
    Posts
    94

    Resolved [RESOLVED]Write function to get all records?

    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


    PHP Code:
    $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;
        } 
    Last edited by rasana; Nov 6th, 2008 at 06:32 AM.

  2. #2
    Frenzied Member the182guy's Avatar
    Join Date
    Nov 2005
    Location
    Cheshire, UK
    Posts
    1,473

    Re: Write function to get all records?

    Hi rasana,

    Here's a function similar to yours, that will return whats known as a 'jagged' array - basically an array where each element is another array. So in this case, each element of the first array is a set of data about a single student.

    PHP Code:
    function getRecords($sql)
    {
        
    $output = array();
        
        
    $res mysql_query($sql);
        
        while(
    $row mysql_fetch_assoc($res))
        {
            
    //loop through each row returned, and store it in an array to return
            
    $output[] = $row;
        }
        
        return 
    $output;

    Here's one way to loop through the data and display it:
    PHP Code:
    $students getRecords("SELECT * FROM students");

    foreach(
    $students as $student)
    {
        
    //here you now have access to all the fields from the table
        
    echo $student['name'];

    You could add some code to check that some rows were returned from the query, and possibly return false if none found, then when processing the array you can check if the result was false or is_array().

    If you don't fully understand how the result array of the function works, do a print_r($students) and it will show you.
    Last edited by the182guy; Nov 6th, 2008 at 06:08 AM.
    Chris

  3. #3

    Thread Starter
    Lively Member rasana's Avatar
    Join Date
    Jan 2007
    Location
    Mumbai, (India)
    Posts
    94

    Re: Write function to get all records?

    Thank you the182guy!!!!
    its working..

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width