【发布时间】:2018-09-03 11:02:04
【问题描述】:
我对 PHP 和 SQL 比较陌生。我正在开发一个应该包含聊天功能的小型 PHP 网站。现在我的数据库中有一个名为“friendchat”的表。这有五列:receiver、sender、message、date、message-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
因此,当我运行代码时,我没有收到任何错误消息或任何通知,但数据不在我的数据库中。我无法弄清楚问题可能是什么。有人可以帮帮我吗?如果您需要任何其他信息,请询问我。
【问题讨论】:
-
数据库通常不会自己给出错误信息,你必须明确地询问。请阅读你如何使用你在那里使用的数据库类。现在你只是触发了查询,但你根本不关心它是否真的成功了,如果没有,为什么不成功。
-
始终在
INSERT! 中明确提及目标列!在这种情况下,您可以将SELECT和INSERT组合成一个语句,例如INSERT INTO friendchat (<target columns>) SELECT id, :sender, :message, \'\', \'\' FROM users WHERE username=:username。这样可以为您节省一趟往返时间。 -
在 PHP 中启用错误报告并检查您会得到什么。将这些添加到您的 php 文件 ini_set("display_errors", "1"); error_reporting(E_ALL);
标签: php html sql mysqli sql-insert