0

我目前正在尝试从我正在对连接到 MySql 数据库的 PHP 文件进行的 ajax 调用中检索多行。

我的代码如下所示:

jQuery/HTML

<script>
$(document).ready(function(){

function getComments(){
var boxid = document.location.hash.substring(1); // remove #    
    $.ajax({ //Make the Ajax Request
             type: "POST",
             url: "getComments.php", //file name
             data: {boxid: boxid},
             success: function(server_response){        
                var data = $.parseJSON(server_response);
                var html = '', comment;
                for(var i = 0; i < data.length; i++){
                    comment = data[i];
                    html += '<div id="' + comment.user_id + '"><span>' + comment.username + '</span><span>' + comment.comment + '</span></div>';
                }
                $('#ajax_comment').html(html);

             }
         });
}

});
</script>
<span name="ajax_comment" id="ajax_comment"></span>

PHP (getComments.php)

session_start();
include('config.php');
if (isset($_SESSION['userid']))
$userid = $_SESSION['userid'];
else
$userid = 0;

if (isset($_POST['boxid']))
{
$knownid = $_POST['boxid'];
$query = mysql_query("SELECT u.id, u.USERNAME, c.COMMENT, c.DATE_ADDED, c.ACTIVE, c.id FROM ratemybox.USERS u, ratemybox.COMMENTS c WHERE u.id = c.user_id and c.box_id = $knownid ORDER BY c.DATE_ADDED DESC");

$result = mysql_fetch_array($query);
$results = array();
foreach($result as $row)
{
    $user_id = $row['id'];
    $username = $row['username'];
    $comment = $row['comment'];
    $dateAdded = $row['date_added'];

    $results[] = array("user_id" => $user_id, "username" => $username, "comment" => $comment, "date_added" => $dateAdded);
}

echo json_encode($results);
}

这没有产生我期望的结果。任何建议都会很棒。

编辑

使用 Firebug 时出现以下错误:

Illegal string offset 'id' in 
Illegal string offset 'username'
Illegal string offset 'comment'
Illegal string offset 'date_added'

不确定这是否有帮助?

4

2 回答 2

1

在您的选择查询中,您尝试按 $knownid 进行过滤,但是,您将变量保留在引号内。尝试更改为:

   $query = mysql_query("SELECT u.id, u.USERNAME, c.COMMENT, c.DATE_ADDED, c.ACTIVE, c.id FROM ratemybox.USERS u, ratemybox.COMMENTS c WHERE u.id = c.user_id and c.box_id = " . $knownid . " ORDER BY c.DATE_ADDED DESC");
于 2013-02-18T16:25:08.523 回答
0

除了已经给出的许多建议(您确实需要在将 $_POST["boxid"] 添加到查询之前将其转义)之外,很难找到代码的问题而不会出现一些错误。

尝试在 foreach 之前添加 var_dump($result) 以确保您的查询正在返回某些内容,或者检查浏览器的控制台以查看服务器实际返回的内容。

于 2013-02-18T16:37:29.447 回答