-2

this is my code for getting the input of two text fields, sender and message. However, my webpage keeps giving me this error: Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in C:\Users\Administrator\Desktop­\xampp\htdocs\Chat\includes\Fu­nctions\Chat.func.php on line 11. Please help me. I looked around and most are saying that this error occurs because maybe the $query is incorrect. However, my db_name and tbl_name are correct and everything else in the $query is as well.

function get_msg(){

        $query = "SELECT 'Sender', 'Message' FROM 'db_name'.'tbl_name'";

        $run = mysql_query($query);

        $messages = array();

        while($message = mysql_fetch_assoc($run)){
            $message[] = array('sender' => $message['Sender'], 
                               'message' => $message['Message']);
        }

        return $messages;

    }
Karthik
  • 21
  • 1
  • 5

2 Answers2

3

Replace the apostrophes with backticks:

$query = "SELECT `Sender`, `Message` FROM `db_name`.`tbl_name`";

Apostrophes denote string constants in SQL, while MySQL uses backticks to escape internal names like fields or tables in case they conflict with reserved words. Your query in this case will actually also work fine without any backticks.

Second off, showing mysql errors would've shown you this (append or die(mysql_error()) to the query line of code), or actually copy/pasting your query into phpMyAdmin for example.

Finally, the mysql_query family of functions is deprecated as of PHP 5.5. You should switch to PDO or mysqli instead.

Niels Keurentjes
  • 39,856
  • 8
  • 91
  • 133
1

1) mysql_query is failing and returning false. 2) use mysqli extension. mysql_* is deprecated. 3) use backticks instead of single quotes

You need to use backticks instead of 'single quotes'. Otherwise you are just selecting strings. Same goes for the column, database and table names. That is why your query is failing assuming the columns, database and tables exist.

km6zla
  • 4,712
  • 1
  • 27
  • 49