behaviour of mysql_fetch_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
korvirlol
Forum Newbie
Posts: 4
Joined: Fri Jul 03, 2009 4:02 pm

behaviour of mysql_fetch_array

Post 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!
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: behaviour of mysql_fetch_array

Post 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;       
    }
}
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
Post Reply