Reputation: 14210
I have the following table in MySQL:
╔══════╦════╗
║... City.....║...ZIP..║
╠══════╬════╣
║ Prague. ║ 11000║
║ Brno..... ║ 34785║
╚═══════════╝
The following code works:
Class Mysql{
function connect(){
$this->c = new mysqli(
$this->OPTION['dbhost'],
$this->OPTION['dbuser'],
$this->OPTION['dbpass'],
$this->OPTION['dbname']
);
if($this->c->connect_errno){
exit("Connect failed: ".$this->c->connect_error);
}
if(!$this->c->select_db($this->OPTION['dbname'])){
exit("Cannot select the database: ".$this->OPTION['dbname']);
}
}
function query($query){
if(!$this->c->query($query)){
exit("Cannot execute the query: {$query}<br>MySQL Error: {$this->c->error}<br>MySQL Error Code: {$this->c->errno}");
}
return $this->c->query($query);
}
function fetch_assoc($result){
return $result->fetch_assoc();
}
}
$DB = new Mysql;
$DB->connect();
$query = $DB->query("SELECT city, ZIP FROM cities");
while($row = $DB->fetch_assoc()){
print_r($row);
}
The code works until I try to change fetch_assoc part like this:
function fetch_assoc($query){
$result = $this->query($query);
return $result->fetch_assoc();
}
}
$DB = new Mysql;
$DB->connect();
while($row = $DB->fetch_assoc("SELECT city, ZIP FROM cities")){
print_r($row);
}
In this case it endlessly (stopped by max execution time) prints the first row of the table: Array ( [City] => Prague [ZIP] => 11000 )
Upvotes: 4
Views: 205
Reputation: 5894
I believe this should do it, it would be making the query once and iterating over it as mentioned in my comments above:
$DB = new Mysql;
$DB->connect();
$query = $DB->query("SELECT city, ZIP FROM cities");
$result = $DB->fetch_assoc();
while ($row = $result->fetch_assoc()) print_r($row);
Upvotes: 2