MySQL Fetch Problem

Discussion in 'PHP' started by neha2011, Apr 28, 2011.

  1. #1
    I have written a db function in my lib as

    function RunSQL($sql)
    {
        define('BASEPATH','TEMP');
        include "../../../config/database.php";
    
        /* Connect to the database */
        $link = mysql_connect($db['dbname']['hostname'], $db['dbuser']['username'], $db['pwd']['password']);
        if (!$link) {
            die('Could not connect: ' . mysql_error());
        }
        mysql_select_db($db['db']['database']) or die(mysql_error());
    
        $result = mysql_query($sql);
        while($row = mysql_fetch_assoc($result)){
            $dataset[] = $row;
        }
    
        return $dataset;
    }
    PHP:
    Then in my class, I call this function and try to go through records as:

            $rs_transactions = RunSQL($sql);
            print_r($rs_transactions);
    
            foreach($rs_transactions as $row)
            {
                echo "<br><br>...in loop....";
            }
    PHP:
    Problem is that print_r shows there r three records returned, but in foreach loop, it goes through only for first record. It doesn't loop for all three records.

    What could be wrong?
     
    neha2011, Apr 28, 2011 IP
  2. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #2
    Can you post the array in print_r($rs_transactions);
     
    jestep, Apr 28, 2011 IP
  3. lioncub5

    lioncub5 Peon

    Messages:
    27
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    the call to your RunSQL function is not inside the foreach loop, which is why it only runs once.
    It needs to be more like this:
     
    
            foreach($rs_transactions as $row)
            {
           print_r(RunSQL($row));        
           echo "<br><br>...in loop....";
            }
    PHP:
     
    lioncub5, Apr 29, 2011 IP
  4. lioncub5

    lioncub5 Peon

    Messages:
    27
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    my bad. i misunderstood what you were trying to do.
    in your runSQL function, try getting rid of the while statement
    just do:
    $row=mysql_fetch_assoc($result);
     
    lioncub5, Apr 30, 2011 IP