如何在PHP中返回从MySQL获取的数组

时间:2015-11-15 20:43:04

标签: php mysql arrays

我正在尝试从存储在PHP文件中的公共函数返回一个调用的数组。 我需要导出的返回数组是JSON格式。 我有以下代码用于调用数组(在其他情况下工作),但输出只是数组(phpMyAdmin中的sql返回所有数据)

这是应该返回数组的公共函数,存储在一般的PHP类文件中。

public function getIssueList() {
    $sql = "select * from IssueData";
    $returnValue = array();

    $result = $this->conn->query($sql); // makes the connection and executes the sql

    if ($result != null) {
        $row = $result->fetch_array(MYSQLI_ASSOC);
        if (!empty($row)) {
            $returnValue = $row;
        }
    }

    return $returnValue;

}

然后我从下面的代码中调用公共函数:

$result = $dao->getIssueList(); //opens the connection and calls the public function

echo $result;

但我得到的回声结果只是"数组"

上面的代码适用于其他公共函数,但在这种情况下它只返回一行而不是多行。 此外,我需要将数组作为关联。

可能出现什么问题?

4 个答案:

答案 0 :(得分:0)

你可以json_encode(http://php.net/manual/en/function.json-encode.php

echo json_encode($result);

答案 1 :(得分:0)

你必须将$ result作为json_encode($ result)返回,以正确填充你的数组你必须做$ returnValue [] = $ row;

(你可能想做一个while循环来填充你的数组)

答案 2 :(得分:0)

要获得多行而不是一行,请使用while循环:

if ($result != null) {
$row = $result->fetch_array(MYSQLI_ASSOC);
    while(!empy($row)){
        $returnValue = array_merge($returnValue, $row);
        $row = $result->fetch_array(MYSQLI_ASSOC);
    }
return $returnValue; 
}

答案 3 :(得分:0)

好吧,问题主要在于我使用的是echo而不是print_r。

还改为代码:

<?php
echo'<form method="post" action="">';
echo '<input type=text name=t/>';
echo'<input type=submit name=su/>';
echo'</form>';
if(isset($_POST['su']))
{
    if (ctype_digit($_POST['t'])) {
        echo "This is number.\n";
    } else {
        echo "This is not a number.\n";
    }
}
?>

为:

if ($result != null) {
    $row = $result->fetch_array(MYSQLI_ASSOC);
    if (!empty($row)) {
        $returnValue = $row;
    }
}