There is a connection between two tables, the id value in the lobby table should be passed to the id cell, already in the message table. Here is the structure of two tables:

messages : lobby

lobby : lobby

And when I enter a message in the form, the first message for the lobby is added to the database and displayed on the screen, and when I enter the second, nothing is entered into the database and an error appears:

Problem with SQL: INSERT INTO messages (id, message1) VALUES (176, \ 'my text \')

Here is the code that adds to the database:

 <?php require_once 'config.php'; $message = FormChars($_POST['message']); // Получаем форму $db->query('SELECT * FROM lobby'); // Получаем id нашего lobby ... $data = $db->Get(); foreach ($data as $key => $value) { $lobby_id = $value['id']; // ... Получили } // Вносим в таблицу messages - id нашего лобби и само сообщение $db->Query("INSERT INTO messages(id, message1) VALUES ($lobby_id, '$message')"); echo $message; ?> 

I would be very grateful if someone responds ...

  • one
    Your messages.id field is unique? Primary key? If yes, then the same values ​​of $ lobby_id cannot be placed in it, as it happens when placing the second answer. - cheops
  • Offtopic: the part "Get the id of our lobby" is a ready-made anti-example. No need to read the entire table to get one scalar value. It is not clear what kind of ID you will receive - there is no limiting condition. Somewhere there must be a WHERE ! - artoodetoo

1 answer 1

id - a unique key in the messages table? Add a new lobby_id field to the messages table and lobby_id

 $db->Query("INSERT INTO messages(id, message1) VALUES ($lobby_id, '$message')"); 

on

 $db->Query("INSERT INTO messages(lobby_id, message1) VALUES ($lobby_id, '$message')"); 
  • Yeah. It works, thanks man. - Bim Bam
  • one
    @BimBam if the answer helped solve your problem, do not forget to mark it as "Best" - lolbas