繁体   English   中英

使用php / javascript(ajax)从数据库(SQL)到网站前端显示多行

[英]Show multiple rows from database(SQL) using php/javascript(ajax) to front end of website

我对php和javascript(ajax)还是很陌生,我尝试查看各种帖子和网站来寻找答案,但无济于事。

我正在尝试在网站的前端显示数据库中所有相关的行。 我的SQL语句当前正在提取我需要的所有行,但无法显示全部行(我只能显示一行)。

有人可以指导我一点,告诉我怎么做才能正确吗? 我的代码如下:

PHP-

$result = mysql_query("SELECT lot_num, buyer_id, item_desc, quantity, price FROM auction_items where auction_id = (SELECT id FROM auction ORDER BY date_created desc Limit 1) ORDER BY id DESC");          //query

    $table_data = array();
   while($row = mysql_fetch_array($result)){
       $table_data[]= (array('lot_num' => $row["lot_num"], 'buyer_id' => $row["buyer_id"], 'item_desc' => $row["item_desc"], 'quantity' => $row["quantity"], 'price' => $row["price"]));
    }
   // $array = mysql_fetch_row($result);    

    echo json_encode($table_data);

我还将包括我的javascript(ajax)代码以涵盖基础知识:

$("#submit").click(function(){
    $.ajax({                                      
        url: 'auctionItemLoad.php',      //the script to call to get data          
        dataType: 'json',                //data format      
        success: function(data)          //on recieve of reply
        {
            var lot_num = data[0];              
            var buyer_id = data[1];           
            var item_desc = data[2];
            var quantity = data[3];
            var price = data[4];
            $('#lot_num_result').html(lot_num);
            $('#buyer_id_result').html(buyer_id);
            $('#item_desc_result').html(item_desc);
            $('#quantity_result').html(quantity);
            $('#price_result').html(price);
        }
        });
    });

仅显示一行的原因是因为您仅访问数据的第一行,所以必须迭代所有行以显示其所有数据。 就像您对php文件中所有sql请求的结果行进行迭代以将它们添加到$table_data数组中一样,您必须对ajax请求的成功回调中的data进行迭代,这一次将输出数据。 您可以使用JQuery的each函数来做到这一点。

...
success: function(data) {
    $.each(data, function(i, row) {
        var lot_num = row.lot_num;              
        var buyer_id = row.buyer_id;           
        var item_desc = row.item_desc;
        var quantity = row.quantity;
        var price = row.price;

        $('#lot_num_result').append(lot_num);
        $('#buyer_id_result').append(buyer_id);
        $('#item_desc_result').append(item_desc);
        $('#quantity_result').append(quantity);
        $('#price_result').append(price);
    )};
}
...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM