I will start by apologizing for not even knowing what to search for. So I'm asking a question that may have already been answered.
I am using the sql.phpm example out of your book "Professional PHP 5" from chapter 7. After adapting it to mysql and debugging it, I have beat my head against the wall over and over because I when I call GetRowHash(0), what I get back seems to be useless. It appears to be an array containing a result row. I try to access it using either:
Code:
$record = $sql->GetRowHash(0);
foreach ($record as $key => $value) {
print $key ." = " . $value;
}
or
Code:
$ss = $record['ss'];
and I get nothing. Please help me to understand how I can use this result array properly. I have included the modified sql.phpm file.
Code:
<?php
class sql {
private $result_rows; # Result rows hash
private $query_handle; # db: the query handle
private $link_ident; # db: the link identifier
private $num_rows; # db: count rows returned
public function __construct() {
/* Define connection details to the MySQL server */
define("DB_HOST", "localhost");
define("DB_USER", "someuser");
define("DB_PASS", "password");
$db_name = "PCPD";
$this->link_ident = mysql_connect(DB_HOST, DB_USER, DB_PASS) OR die("Cannot connect to MySQL server!");
mysql_select_db($db_name);
}
public function Query($sql, $code_return_mode = 0) {
$querytype = substr($sql, 0, strpos($sql, ' '));
$result = mysql_query($sql)or die('Query failed: ' . mysql_error() . "<br />\n$sql"); ;
if (!$result) {
error_log("QUERY FAILED: $sql\n");
return(0);
}
if ($querytype == 'INSERT' | $querytype == 'UPDATE' | $querytype == 'REPLACE' | $querytype == 'DELETE') {
if (mysql_affected_rows() > 0) { // mysql_affected_rows() = INSERT, UPDATE, REPLACE or DELETE Statements
$this->num_rows = mysql_affected_rows();
}
}
else {
if (mysql_num_rows($result) > 0) {
$this->num_rows = mysql_num_rows($result); //Only SELECT Statements
for ($i=0; $i <= mysql_num_rows($result)-1; $i++) { // mysql_num_rows() = SELECT Statements
$resultarray = mysql_fetch_array($result);
$return_array[$i] = $resultarray;
}
$this->result_rows = $return_array;
return(1);
}
else {
$this->num_rows = 0;
return(0); # return 0 if it fails
}
}
}
public function GetNumRows() {
return ($this->num_rows);
}
public function GetResult($row_num, $column_name) {
return ($this->result_rows[$row_num][$column_name]);
}
public function GetRowHash($row_num) {
return ($this->result_rows[$row_num]);
}
public function GetTableHash() {
return $this->result_rows;
}
public function Done($close_connection = 0) {
if ($close_connection) {
mysql_close($this->link_ident);
}
}
}
?>
Thanks, Bill