试图将sql中的行数输出到jquery

时间:2011-05-11 00:10:20

标签: php jquery mysql

我已经按照教程向页面异步添加注释。这一切都有道理,但现在我想改变它只显示mySql表中注释数的计数。我试图在逻辑上改变它,但我似乎迷失了如何正确地将数据从php传递到jquery函数?

以下是原始工作评论代码:

的javascript

<script type="text/javascript">  

$(function() {  
    //retrieve comments to display on page  
  $.getJSON("comments.php?jsoncallback=?", function(data) {  


   //loop through all items in the JSON array  
   for (var x = 0; x < data.length; x++) {  

     //create a container for each comment  
     var div = $("<div>").addClass("row").appendTo("#comments");  

     //add author name and comment to container  
     $("<label>").text(data[x].name).appendTo(div);  
     $("<div>").addClass("comment").text(data[x].comment).appendTo(div);  
   } 
  });  
});  
</script>

还有comments.php

<?php  

  //db connection detils  
  $host = "localhost";  
  $user = "***";  
  $password = "***";  
  $database = "comments";  

  //make connection  
  $server = mysql_connect($host, $user, $password);  
  $connection = mysql_select_db($database, $server);  

  //query the database    
    $query = mysql_query("SELECT * FROM comments");  

    //loop through and return results  
    for ($x = 0, $numrows = mysql_num_rows($query); $x < $numrows; $x++) {  
        $row = mysql_fetch_assoc($query);  

        $comments[$x] = array("name" => $row["name"], "comment" => $row["comment"]);  
      }  

  //echo JSON to page  
  $response = $_GET["jsoncallback"] . "(" . json_encode($comments) . ")";  
  echo $response; 

?>

这就是我试图改变它们的方式:

的javascript

<script type="text/javascript">  

$(function() {  
    //retrieve comments to display on page  
  $.getJSON("comments.php?jsoncallback=?", function(data) {  

     var div = $("<div>").addClass("row").appendTo("#comments");   
     $("<label>").text(data).appendTo(div);  


  });  
});  
</script>

还有comments.php

<?php  

  //db connection detils  
  $host = "localhost";  
  $user = "***";  
  $password = "***";  
  $database = "comments";  

  //make connection  
  $server = mysql_connect($host, $user, $password);  
  $connection = mysql_select_db($database, $server);  

  //query the database    
    $query = mysql_query("SELECT COUNT (*) FROM comments");  

    //return results  
    $numrows = mysql_num_rows($query); 

  echo $numrows; 

?>

这对我来说似乎不起作用。我没有得到任何错误,但查询的结果没有被添加到页面?非常感谢任何帮助,提前谢谢。

1 个答案:

答案 0 :(得分:0)

关于@mellamokb所说的,你需要抓住第一行(包含计数),而不是返回的行数。而不是$numrows = mysql_num_rows($query);,请尝试使用$row = mysql_fetch_array($query); $count = $row[0];行。 $count应该是评论的数量。