SQL代码没有错误,但不会从数据库中获取数据

时间:2018-09-03 11:02:04

标签: php html sql mysqli sql-insert

我对PHP和SQL比较陌生。我正在一个小型PHP网站上工作,该网站应该包含聊天功能。现在,我的数据库中有了一个名为“ friendchat”的表。它具有五列:收件人,发件人,消息,日期,消息ID。日期列来自日期时间类型,消息ID为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 :(得分:1)

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

打印出$ receiver_id的值以进行调试

您是否获得了$ receiver_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(); 

在此处停止代码,以便您可以在网络浏览器的网络标签(Chrome中为F12)中看到var_dump输出

如果到此为止却没有看到任何错误,请尝试使用上述变量中​​的确切值将插入查询写入phpmyadmin(直接写入数据库),如果出了问题,数据库应该给您一个更具体的错误从

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