【问题标题】:Why doesn't my ajax work with prepared mysqli statement为什么我的 ajax 不能与准备好的 mysqli 语句一起使用
【发布时间】:2014-04-14 17:32:50
【问题描述】:

我有一个小问题,即当我将准备好的语句添加到 PHP 文件中时,Ajax 停止工作并给我一个 500- 错误,但是当我删除该语句时,它就像一个魅力。

这是我的 PHP 文件:

<?php 
include ('db_connect.php');
include ('functions.php');

$datad = $_POST['superstr'];
$id = 1;

    $stmt = $mysqli->prepare("UPDATE `song` SET `lyrtext`=? WHERE `id`=?");
    $stmt->bind_param("si", $datad, $id);
    $status = $stmt->execute();

echo $datad;
?>

我的 Ajax 看起来像这样:

$.ajax({
          url: 'includes/sendlyrics.php',
          type: 'POST',
          data: {superstr: 'pelle'},
          success: function(data) {
            //called when successful
            var hello = data;
            //prompt(data);
            console.log("The data is:");
            console.log(data);
            console.log("The variable which should keep the data has this content:");
            console.log(hello);
          },
          error: function(e) {
            //called when there is an error
            console.log(e.message);
            prompt(e.message);
            //alert(e.message);
          }
        });

有什么问题?

【问题讨论】:

  • 你有没有像$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');一样启动mysqli?
  • 您是否查看过控制台以查看报告了哪些错误?当 AJAX 不调用 PHP 时,它自己工作吗?
  • 这是它在控制台中所说的:POST http://superaudio.web/AudioThingy/includes/sendlyrics.php 500 (Internal Server Error) ,是的,这是我的连接:$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE); mysqli_set_charset($mysqli,'utf8'); if ($mysqli-&gt;connect_error) { header("Location: ../error.php?err=Unable to connect to MySQL"); exit(); }
  • 您收到 500 错误,这意味着服务器级别的 PHP 失败。查看服务器错误日志,看看是否有任何关于它失败原因的线索,AJAX 似乎工作正常。 PHP 自己工作吗?
  • 请参阅这篇文章以了解如何正确调试 AJAX 调用,请随时投票。 stackoverflow.com/a/21617685/2191572

标签: php jquery mysql ajax mysqli


【解决方案1】:
$stmt = $mysqli->prepare("UPDATE `song` SET `lyrtext`=? WHERE `id`=?");
$stmt->bind_param("si", $datad, $id);
$status = $stmt->execute();

错了。修改为:

$stmt = $mysqli->prepare("UPDATE `song` SET `lyrtext`=? WHERE `id`=?");
$stmt->bind_param("si", $datad, $id);
$stmt->execute();

如果您正在寻找查询是否成功执行的确认,您可以通过以下方式进行测试:

if($stmt->execute()){
    //returned true - statement executed successfully
} else{
    //returned false
}

您还应该将您的 Ajax 调用修改为类似于:

$.ajax({
url     : "your/url/here.php"
type        : "POST",
data        : {superstr: 'pelle'},
dataType    : "json",
success     : function(data){
        //do something with the response
},
error           : function(jqXHR, textStatus, errorThrown){
        //handle the error
}
});

通过添加 json 的 dataType,您应该将 .php 文件的 echo 语句修改为:

$response = Array();
array_push($response, $datad);
echo json_encode($response);

我确定您已经在线阅读过文档,但可以找到 Ajax here,并准备好语句 here

这一切都写有警告,即您的数据库连接是有效的......它似乎给出了您问题的措辞,以及您之前解决问题的尝试。

【讨论】:

    猜你喜欢
    • 2011-07-09
    • 1970-01-01
    • 1970-01-01
    • 2015-12-07
    • 2018-10-21
    • 2023-03-26
    • 2012-12-01
    • 1970-01-01
    • 2013-07-23
    相关资源
    最近更新 更多