Page 1 of 1

behaviour of mysql_fetch_array

Posted: Tue Mar 16, 2010 3:47 pm
by korvirlol
Hi there,

I am a reasonably experienced php developer but havent run into this before.

I am trying to abstract usage of mysql functions for a project we are working on (yes i am aware of mdb2), but there is one big roadblock i am running into.

In mysql, if you are not querying on a primary key you must do something like: while($resource = mysql_fectch_array){}

in my abtracted object, i want to emulate this kind of functionality (as opposed to just returning an array of all of the values from the query, which would be simple enough to do).

Does anyone know how i could go about doing this?

thanks for any help!

Re: behaviour of mysql_fetch_array

Posted: Tue Mar 16, 2010 6:06 pm
by AbraCadaver
Here's a very simplistic example just to illustrate (not tested) and it's missing lots of error checking etc. Here you can fetch the next record or all. Also, I used mysql_fetch_object() to be consistent since you're using an object for the DB:

Code: Select all

class mydb {
 
    private $connection;
    private $result;
 
    function __construct($host, $user, $pass) {
        $this->connection = mysql_connect($host, $user, $pass);
    }
 
    function query($sql) {
        if($this->result = mysql_query($query)) {
            return true;
        }
        return false;
    }
 
    function fetchNext() {
        return mysql_fetch_object($this->result);
    }
 
    function fetchAll() {
        $rows = array();
 
        while($row = mysql_fetch_object($this->result)) {
            $rows[] = $row;
        }
        return $rows;       
    }
}