繁体   English   中英

使用mysql将多个列值分配给JSON php数组

[英]Assign multiple column values to JSON php array using mysql

我必须提出一个JSON ajax请求并返回一个数组。

我在其他多个问题上找到了此代码(已编辑为我的问题):

var hej[];
function ajax_search(){ 
    $.getJSON('test.php',function(response){
    var data = response.get_response;
    for (i in data){
      hej.push([i,data[i]]);
    }
alert(hej[0]);
}

在php部分中,我有一个数据库,我需要从中获得数据,我有5列pr。 行。 我只有一行,而且我需要数组中的所有五列。

$sql = "SELECT * FROM 'table'
   LIMIT 1 OFFSET $i"; //random offset
$result = mysql_query($sql);

$storeArray = Array();
while($row = mysql_fetch_array($result))
{
    $storeArray[0]=$row['column1'];
    $storeArray[1]=$row['column2'];
    $storeArray[2]=$row['column3'];
    $storeArray[3]=$row['column4'];
    $storeArray[4]=$row['column5'];
}
$json = json_encode($storeArray);
echo $json;

我知道即时通讯做错了事,而且我是编程新手。 调用后,我需要能够访问我的JavaScript中的所有列值,并在其他函数中使用它们,但我无法使其返回。

如果其中任何一个出现错误,我都会向javascript和php寻求帮助。

为什么要使用response.get_response?

var hej[];
function ajax_search(){ 
    $.getJSON('test.php',function(data){
    $.each(data, function (i,item) {
      hej.push([i,item]);
    }
alert(hej[0]);
}

尝试这个:

JavaScript代码:

var hej[];
function ajax_search(){
    $.getJSON('test.php',function(response){
        $.each(response.results, function(key, val) {
            hej.push(val);
        });
        alert(hej[0]);
    });
}

PHP代码:

<?php
$sql = "SELECT * FROM 'table' LIMIT 1 OFFSET $i"; //random offset
$result = mysql_query($sql);

$storeArray = array();
while($row = mysql_fetch_array($result)) {
    $storeArray[0]= $row['column1'];
    $storeArray[1]=$row['column2'];
    $storeArray[2]=$row['column3'];
    $storeArray[3]=$row['column4'];
    $storeArray[4]=$row['column5'];
}

$json = json_encode( array('results' => $storeArray ) );
echo $json;
?>

希望这可以帮助。

它应该是:

function ajax_search(){ 
    $.getJSON('test2.php',function(response){
        // response.column1
        // response.column2
        // response.column3

        // for array push:
        var hej = [];
        $.each(response, function(key, val) {
             hej.push(val);
        });
        alert(hej[0]); // it will alert column1
    });

}

和MySQL:

$sql = "SELECT `column1`, `column2`, `column3`, `column4`, `column5` FROM `table` LIMIT 1 OFFSET $i"; //random offset
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
$json = json_encode($row);
echo $json;

暂无
暂无

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

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