首页 > 解决方案 > 未使用 Ajax 将 PHP 记录插入数据库

问题描述

这是 AJAX 请求正文

阿贾克斯

var date = new Date().toLocaleTimeString();
var text=this.value;
var id=1;
$.ajax({
type: "GET",
url: "StoreMessages.php" ,
data: { room: id, msg:text,sendat:date }
});

PHP 代码

 if(isset($_GET['room']))
        {
            $chatroom_name = $_GET['room'];

            if(isset($_GET['msg']))
            {
                $text= $_GET['msg'] ;
                if(isset($_GET['sendat']))
                {
                    $local_time= $_GET['sendat']);
                    insertMessage( $text,$local_time, $chatroom_name);
                } 
            } 
        } 


function insertMessage($message_body,$local_time,$room_id)
{


    echo "<script type='text/javascript'>alert('$message_body');</script>";


    echo "<script type='text/javascript'>alert('$local_time');</script>";


    echo "<script type='text/javascript'>alert('$room_id');</script>";

    $conn = new mysqli($GLOBALS['server'], $GLOBALS['user'], $GLOBALS['pass'], $GLOBALS['db_name']);

    if($conn==false)
        {
            die("unable to connect database");
        }

    $sql="INSERT INTO `message` (`Message_Text`, `Time`, `Conversation_Id`) VALUES ('$message_body', '$local_time', '$room_id')";
    if(mysqli_query($conn,$sql)){
        echo "record inserted successfully"."<br/>";

    }
    else{
        echo "error".mysqli_error($db_conn);
    }

解释

当用户键入消息并按回车键时,ajax 调用触发对于其他变量,我正在尝试将实时聊天存储到数据库

标签: javascriptphpajaxmysqli

解决方案


调试的第一步是/正在诊断故障发生的位置。去做这个:

  1. 打开你的开发者控制台
  2. 转到network选项卡
  3. 进行任何触发 AJAX 请求的操作
  4. network单击选项卡中显示的请求
  5. 转到response选项卡*

*如果请求的状态代码是 500,这也表明脚本在 PHP 端失败。转到服务器并查看错误日志。

从我们在response选项卡中得到的响应中,我们确定问题是这一行的尾括号:

$local_time= $_GET['sendat']);

此外,您应该使用参数化查询。任何字段中的单引号都会中断您的查询。

http://php.net/manual/en/mysqli.quickstart.prepared-statements.php

大致:

$sql="INSERT INTO `message` (`Message_Text`, `Time`, `Conversation_Id`) VALUES (?, ?, ?)";

然后preparebind值和execute查询。

另外我会发回一个 JSON 对象而不是 JS 代码。看看http://php.net/manual/en/function.json-encode.php


推荐阅读