-2

Possible Duplicate:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result

In db.php I have:

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

}
?>

In index.php I have:

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

I am getting the following error: => error: <b>Warning</b>: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource from db.php.

What am I doing wrong?

Community
  • 1
  • 1
Hai Truong IT
  • 4,126
  • 13
  • 55
  • 102
  • I tried to copy paste your code, No Error Found ! Please check your database name, database password, database user or table name. – Zul Dec 19 '11 at 03:57
  • As a rule of thumb, you shouldn't name a local variable the same as your class: 'connect'. Change 'private $connect' to (for instance) 'private $connection'. Then you should use that variable in your query: $query = mysql_query($sql, $this->connection); – dar7yl Dec 19 '11 at 11:40

3 Answers3

6

Try to find what is the error:

  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;
}
check123
  • 1,989
  • 2
  • 22
  • 28
  • 2
    Don't know why this was downvoted. Something is wrong with the query or else it would return a result resource object. Only way to find out is to display the error message. – spatel Dec 19 '11 at 03:54
  • I bet the error message is one of the two things I mentioned :P – Jessedc Dec 19 '11 at 03:59
2

That error is telling you that your query executed by $query = mysql_query($sql); is returning an error. It's not returning zero results, it's returning an error which suggests that your database named 'databasename' or table within that named 'test' doesn't exist.

Jessedc
  • 12,320
  • 3
  • 50
  • 63
0

It sounds like no results are returned from the query or a general query error, do the columns and table in the query exist and is your connection to the database all okay?

Dan
  • 11,914
  • 14
  • 49
  • 112