Javascript 用PHP将从数据库获得的数据输入单独的html的最佳方法是什么<;部门>';s
我目前正在做一个类似Facebook的聊天,有3个不同的聊天框可以同时工作。我可以从我的数据库中发送和读取消息,但是我很难在正确的位置显示这些信息。在Javascript 用PHP将从数据库获得的数据输入单独的html的最佳方法是什么<;部门>';s,javascript,php,html,chat,Javascript,Php,Html,Chat,我目前正在做一个类似Facebook的聊天,有3个不同的聊天框可以同时工作。我可以从我的数据库中发送和读取消息,但是我很难在正确的位置显示这些信息。在chat.php中,我有一段代码: $.ajax({ url: "fetch_user_chat_history.php", method: "POST", data: jQuery.param({receiver_id:receiver_id, num:num
chat.php
中,我有一段代码:
$.ajax({
url: "fetch_user_chat_history.php",
method: "POST",
data: jQuery.param({receiver_id:receiver_id, num:num}),
success: function(data) {
$('$chat_history_'+receiver_id).html(data);
}
});
现在,我能够在fetch_user_chat_history.php
中正确读取数据库中的数据,但当我迭代消息时,无法将它们正确输出回chat.php。这是我的fetch\u user\u chat\u history.php
:
<?php
include "opendb.php";
session_start();
$output1 = '';
$output2 = '';
$increment = 0;
$sender = $_SESSION['user_id'];
$receiver_id = $_POST['receiver_id'];
$chatboxnum = $_POST['num'];
$query = 'SELECT content, timestamp_chat, sender_id FROM messages WHERE (sender_id = '.$sender.' AND receiver_id = '.$receiver_id.' OR (sender_id = '.$receiver_id.' AND receiver_id = '.$sender.'))';
$statement = $db->prepare($query);
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
switch ($chatboxnum) {
case 1:
foreach ($result as $row) {
if ($row['sender_id']==$sender) {
echo '<script>var para = document.createElement("div");';
echo 'para.innerHTML = '.$row["content"].';';
echo 'var att = document.createAttribute("class");';
echo 'att.value = "msg-send";';
echo 'para.setAttributeNode(att);';
echo 'document.getElementById("sendbox-1").appendChild(para);';
echo 'document.body.appendChild(para); </script>';
}
else {
echo "var element = document.getElementById('receivebox-1'); element.classList.add('msg-receive');";
}
$increment += 1;
}
break;
}
?>
PHP代码有效吗?您是否尝试过使用Postman或类似工具直接调用它?您的代码易受SQL注入攻击。您没有正确使用准备好的语句。您需要绑定您的值。您的脚本已打开。甚至你也应该考虑在<代码> MySqLII<<代码>或<代码> PDO< /Case> API中而不是级联的ValueStEngNote:而不是:<代码>数据:jQuery .PARAM({接收者ID:接收方ID,NUM:NUM}),< /C> >,你可以这样做:<代码>数据:{ReleVeluID:NuffrimID,num:num },。不需要jQuery.param()
准备一个已经烘焙了SQLInjection的查询没有任何好处(或意义:)