Код SQL не имеет ошибок, но не получает данные из базы данных - PullRequest
0 голосов
/ 03 сентября 2018

Я относительно новичок в PHP и SQL. Я работаю над небольшим PHP-сайтом, который должен содержать функцию чата. Теперь у меня есть таблица в моей базе данных, которая называется: friendchat. Это имеет пять столбцов: получатель, отправитель, сообщение, дата, идентификатор сообщения. Столбец даты относится к типу datetime, а идентификатор сообщения - A_I. Итак, теперь я написал следующие строки PHP, чтобы вставить сообщение в базу данных. Функция «DB ::» содержится в «classes / DB.php». Этот метод получения и вставки данных работал для меня каждый раз, но теперь это не так:

    
<?php   
session_start();
include 'classes/DB.php'; 
if (isset($_POST['message-submit'])) { //activation of the send-button
    if(isset($_GET['userchat'])){ //this variable gets the name of the user you want to chat with which you could selected on the previous page
    
    $message = $_POST['message']; //gets the data from the textarea
    
    $receiver_id = DB::query('SELECT id FROM users WHERE username=:username', array(':username'=>$_GET['userchat'])[0]['id']);  //here i get the userid from the person i am chating to in order to be able to insert him in the friendchat table as receiver
    
    DB::query('INSERT INTO friendchat VALUES (:receiver, :sender, :message, \'\', \'\')', array(':receiver'=>$receiver_id, ':sender'=>$_SESSION['myid'], ':message'=>$_POST['message']));  //now the message,receiver, the sender, datetime and message-id will be inserted into the database
    
}else{
  echo "Unothorized access!";  //illegal access
}
}
?>

Вот код формы HTML:

<form action="index.php" method="POST" class="message-form">
      <input class="message" type="text" placeholder="message" name="message">
      <input class="submit" type="submit" name='message-submit' value="Send">
      </form> //form for getting the data from the website

Поэтому, когда я запускаю код, я не получаю сообщений об ошибках или каких-либо уведомлений, но данных нет в моей базе данных. Я не могу понять, в чем проблема. Может кто-нибудь, пожалуйста, помогите мне? Если вам нужна дополнительная информация, пожалуйста, спросите меня.

1 Ответ

0 голосов
/ 03 сентября 2018
<?php   
session_start();
include 'classes/DB.php'; 
if (isset($_POST['message-submit'])) { //activation of the send-button
    if(isset($_GET['userchat'])){ //this variable gets the name of the user you want to chat with which you could selected on the previous page

$message = $_POST['message']; //gets the data from the textarea

$receiver_id = DB::query('SELECT id FROM users WHERE username=:username', array(':username'=>$_GET['userchat'])[0]['id']);  //here i get the userid from the person i am chating to in order to be able to insert him in the friendchat table as receiver



var_dump($receiver_id);

распечатать значение $ receive_id для отладки

Получаете ли вы значение для $ receive_id, если нет, вернитесь на шаг и var_dump значение, содержащееся в '$ _GET [' userchat ']) [0] [' id '])'

$returnValue = DB::query('INSERT INTO friendchat VALUES (:receiver, :sender, :message, \'\', \'\')', array(':receiver'=>$receiver_id, ':sender'=>$_SESSION['myid'], ':message'=>$_POST['message']));  //now the message,receiver, the sender, datetime and message-id will be inserted into the database

var_dump($returnValue);

Сохраните результат запроса и поместите его в var_dump. Это позволит вам увидеть, вернули ли вы «true» или «false» из вставки

die(); 

здесь код остановки, чтобы вы могли видеть вывод var_dump на вкладке вашей сети в веб-браузере (F12 в chrome)

если вы зашли так далеко, не увидев никаких ошибок, попробуйте записать запрос вставки в phpmyadmin (непосредственно в базу данных) с точными значениями, указанными в указанных выше переменных, если что-то не так, база данных должна выдать вам более конкретную ошибку работать с

}else{
  echo "Unothorized access!";  //illegal access
}
}
?>
...