mysqli_fetch_assoc在第一行死亡

时间:2014-08-18 04:48:03

标签: php mysqli

我在MySQL中有以下表格:

╔══════╦════╗
║...城市.....║...ZIP..║
╠══════╬════╣
║布拉格。 ║11000║
║布尔诺.....║34785║
╚═══════════╝

以下代码有效:

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);
}

代码有效,直到我尝试更改fetch_assoc部分,如下所示:

  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);
}

在这种情况下,它无休止地(由最大执行时间停止)打印表的第一行: 数组([City] =&gt; Prague [ZIP] =&gt; 11000)

1 个答案:

答案 0 :(得分:2)

我相信这应该这样做,它会进行一次查询并迭代它,如上面的评论所述:

$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);