I know that there are several already out there, but I'm just trying to learn object oriented programming...

I have the following class that I have built that will be a mysql database query class.

<?php

class dbModule
{
private $conn;
private $db_host;
private $db_name;
private $username;
private $password;
private $myError;
private $query;
private $result;
public $data;
private $rows;
private $cols;

function __construct($db)
{
	$this->db_host = "localhost";
	$this->db_name = $db;
	$this->username = "foo";
	$this->password = "bar";
	$this->myError = "Cannot connect to database.  Please try <a href=\"".$_SERVER['PHP_SELF']."\">again</a>.";
	$this->conn = @mysql_connect($this->db_host, $this->username, $this->password) or die(mysql_error());
	mysql_select_db($this->db_name) or die(mysql_error());		
}

public function dbQuery($sql)
{
	$this->query = $sql;
	if($this->query != "")			
	{
		$this->result = mysql_query($this->query, $this->conn) or die(mysql_error());
		$this->data = array();
		$this->data = mysql_fetch_array($this->result);
		return($this->data);
	}
}

public function dbBuildTable($sql)
{
	$this->query = $sql;
	if($this->query != "")			
	{
		$this->result = $this->dbQuery($this->query);
		$this->cols = mysql_num_fields($this->result);
		$this->rows = mysql_num_rows($this->result);
		$this->data = mysql_fetch_array($this->result);
		for($x = 0; $x < $this->rows; $x++)
		{
			for($y = 0; $y < $this->cols; $y++)
			{
				echo('<td>'.$this->data[$x][$y].'</td>');
			}
		}

	}	
}

function __destruct()
{
	mysql_close($this->conn);
}

}

?>

When I instantiate the object with the following code, it only returns a single object. Can someone give me a clue as to what I'm missing?

<?php

// dbModule Test ------------------ ///

require_once('./classes/class.dbModule.php');

$db = new dbModule('intranet');
$data = ($db->dbQuery('SELECT * FROM timeclock'));

print_r($data);

?>

    public function dbQuery($sql)
    {
    $this->query = $sql;
    if($this->query != "")
    {
    $this->result = mysql_query($this->query, $this->conn) or die(mysql_error());
    $this->data = array();
    $this->data = mysql_fetch_array($this->result);
    return($this->data);
    }
    }

    You only fetch one record 🙂. Replace

    $this->data = mysql_fetch_array($this->result);
    

    with

    $count = mysql_num_rows($this->result);
    for($i=0; $i<$count; $i++)
    {
        $this->data[] = mysql_fetch_array($this->result);
    }

    (I guess that could have been

    while($row = mysql_fetch_array($this->result))
    {
        $this->data[] = $row;
    }

    which is not equivalent to

    while($this->data[] = mysql_fetch_array($this->result))
    {}

    but I usually have a habit of wanting to know how many records were returned before fetching them.)

      Write a Reply...