Just started learning php. Create a chat.

Gives an error message:

Warning: mysqli_query () expects at least 2 parameters, 1 given in C: \ xampp \ htdocs \ chat \ includes \ functions \ chat.func.php on line 7 Warning: mysqli_fetch_assoc () expects parameter 1 to be C: \ xampp \ htdocs \ chat \ includes \ functions \ chat.func.php on line 11

What can be wrong?

Here is the code:

<?php function get_msg() { $query = "SELECT 'Sender', 'Message', FROM 'chat'.'chat'"; $run = mysqli_query($query); $messages = array(); while($message = mysqli_fetch_assoc($run)) { $messages[] = array('sender' =>$message['Sender'], 'message'=>$message['Message']); } return $messages; } function send_msg($sender, $message) { if(!empty($sender) && !empty($message)) { $sender = mysqli_real_escape_string($sender); $message = mysqli_real_escape_string($message); $query = "INSERT INTO 'chat'.'chat' VALUES (null, '{$sender}', '$message')"; if($run = mysqli_query($query)) { return true; } else { return false; } } else { return false; } } ?> 
  • one
    Have you tried to translate the error message? - etki

1 answer 1

Before writing to various resources "Save help!" it is necessary to ALWAYS, ABSOLUTELY ALWAYS and WITHOUT EXCEPTIONS to translate the error message. And it will tell you what is wrong. Translation of your error:

Warning: mysqli_query () expects at least 2 parameters, 1 set

We look into your code mysqli_query($query) and the truth is 1 parameter, but you need two. What is wrong? We look into the documentation :

Procedural style

mysqli_query(mysqli $link, string $query [, int $resultmode = MYSQLI_STORE_RESULT ])

link - Procedural style only: Connection ID obtained using mysqli_connect () or mysqli_init ()

Respectively what? That's right: you have not passed this connection ID.

Similarly with mysqli_fetch_assoc ...

  • @AntonKolesnik Taki and documentation on what?)) You translate an error, you see what is wrong with what method or construction - you look at the docks, what you did wrong. If everything is done as described in the docks, and you still have errors, then it's time to ask someone. And so .... you do not open the docks, right? - Alexey Shimansky
  • @AntonKolesnik should look like this: $run = mysqli_query($link, $query); ..... where $link is the result of connecting $link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db"); ...... That is, in your case, the only option (working but bad) is to use it as a global variable function get_msg() { global $link; $query = "SELECT 'Sender', 'Message', FROM 'chat'.'chat'"; $run = mysqli_query($link, $query); function get_msg() { global $link; $query = "SELECT 'Sender', 'Message', FROM 'chat'.'chat'"; $run = mysqli_query($link, $query); ........... - Alexey Shimansky