Simple Ajax Jquery script- How can I get information for each of the rows in the table?

前端 未结 2 728
慢半拍i
慢半拍i 2020-12-16 04:56

I\'m following a simple ajax>php>mysql example posted here http://openenergymonitor.org/emon/node/107

I can only display information from the first row. My table is

相关标签:
2条回答
  • 2020-12-16 05:37

    The old MySQL extension mysql is outdated, better use mysqli or PDO!

    mysql_fetch_row() returns only 1 row! You have to put it into a loop, for example:

    $data = array();
    while ( $row = mysql_fetch_row($result) )
    {
      $data[] = $row;
    }
    echo json_encode( $data );
    

    You also have to change the JavaScript:

    $.ajax({                                      
      url: 'api.php', data: "", dataType: 'json',  success: function(rows)        
      {
        for (var i in rows)
        {
          var row = rows[i];          
    
          var id = row[0];
          var vname = row[1];
          $('#output').append("<b>id: </b>"+id+"<b> name: </b>"+vname)
                      .append("<hr />");
        } 
      } 
    });
    

    By the way I would recommend you to use mysql_fetch_assoc() because it makes your code more flexible and cleaner.

    0 讨论(0)
  • 2020-12-16 05:38
    $result = mysql_query("SELECT * FROM $tableName");
    $array = array(mysql_fetch_row($result));
    
    // To store every row in the $array
    while($row = mysql_fetch_row($result)) { 
        $array[] = $row; 
    } 
    echo json_encode($array);
    
    0 讨论(0)
提交回复
热议问题