错误警告:php中的mysql_fetch_assoc()

时间:2011-12-19 03:40:10

标签: php

  

可能重复:
  Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result

在db.php中我有:

<?php
class connect {

    private $host = "localhost";
    private $user = "root";
    private $pass = "";
    private $database = "databasename";
    private $connect = null;

    function connect() {
        $this->connect = mysql_connect($this->host, $this->user, $this->pass) or die("Can't connect database");
        mysql_select_db($this->database, $this->connect);
    }

    function getData() {
        $data = array();
        $sql = 'Select * From test';
        $query = mysql_query($sql);
        while($row = mysql_fetch_assoc($query)) {
            $data[] = array($row['id'], $row['name']);
        }
        return $data;
    }

}
?>

在index.php中我有:

<?php
include 'db.php';
$connect = new connect();
$connect->connect();
$data = $connect->getData();
$str = '';
foreach ($data as $dt) {
    $str .= $dt[1];
}
echo $str;
?>

我收到以下错误: =&GT;来自db.php的error: <b>Warning</b>: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource

我做错了什么?

3 个答案:

答案 0 :(得分:6)

尝试找出错误:

  function getData() {
    $data = array();
    $sql = 'Select * From test';
    $query = mysql_query($sql);
    if(!$query) 
    {
     echo 'Error: ' . mysql_error(); /* Check what is the error and print it */
     exit;
    }

    while($row = mysql_fetch_array($query)) {  /* Better use fetch array instead */
        $data[] = array($row['id'], $row['name']);
    }
    return $data;
}

答案 1 :(得分:2)

该错误告诉您$query = mysql_query($sql);执行的查询返回错误。它没有返回零结果,它返回错误,这表明名为'databasename'的数据库或名为'test'的表中的数据库不存在。

答案 2 :(得分:0)

听起来没有从查询返回结果或一般查询错误,查询中的列和表是否存在并且您与数据库的连接是否一切正常?

相关问题