PHP json_encode在MySQL表的第一个索引上返回空数组

时间:2015-06-06 18:14:57

标签: php mysql arrays json mysqli

您好我是PHP的新手,我正在尝试从MySQL表中获取数据作为JSON数组。我确实从PHP文件中获取了JSON数组,但第一个索引上有一个空数组。

这是我在MySQL上创建的表结构:

CREATE TABLE IF NOT EXISTS `tbl_employee` (
  `employee_id` int(4) NOT NULL AUTO_INCREMENT,
  `employee_name` varchar(60) NOT NULL,
  `designation` varchar(30) NOT NULL,
  `hired_date` date NOT NULL,
  `salary` int(10) NOT NULL,
  PRIMARY KEY (`employee_id`),
);

INSERT INTO `tbl_employee` (`employee_id`, `employee_name`, `designation`, `hired_date`, `salary`) VALUES
(1, 'Steve', 'VP', '2013-08-01', 60000),
(2, 'Robert', 'Executive' '2014-10-09', 20000),
(3, 'Luci', 'Manager', '2013-08-20', 40000);
(4, 'Joe', 'Executive', '2013-06-01', 25000);
(5, 'Julia', 'Trainee', '2014-10-01', 10000);

这是我的PHP文件:

<?php
    //open connection to mysql db
    $dbhost = 'clvm.ddns.net:8026';
    $dbuser = 'root';
    $dbpass = '';
    $dbname = 'ta_trial';
    //$conn = mysql_connect($dbhost, $dbuser, $dbpass);

    $connection = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname) or die("Error " . mysqli_error($connection));

    //fetch table rows from mysql db
    $sql = "select * from tbl_employee";
    $result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));

    //create an array
    $emparray[] = array();
    while($row =mysqli_fetch_assoc($result))
    {
        $emparray[] = $row;
    }

    echo json_encode($emparray);
?>

这就是我得到的:

[[],{"employee_id":"1","employee_name":"Steve","designation":"VP","hired_date":"2013-08-01","salary":"60000"},{"employee_id":"2","employee_name":"Robert","designation":"Executive","hired_date":"2014-10-29","salary":"20000"},{"employee_id":"3","employee_name":"Luci","designation":"Manager","hired_date":"2013-08-20","salary":"40000"},{"employee_id":"4","employee_name":"Joe","designation":"Executive","hired_date":"2013-06-01","salary":"25000"},{"employee_id":"5","employee_name":"Julia","designation":"Trainee","hired_date":"2014-10-01","salary":"10000"}]

我不明白为什么第一个索引上会有一个空数组?谁能指出错误或我在这里做错了什么?有没有更好的解决方案呢?谢谢,真的很感激任何帮助。

1 个答案:

答案 0 :(得分:2)

你错过了一些$ emparray [] = array();到 $ emparray = array();

&#13;
&#13;
<?php
    //open connection to mysql db
    $dbhost = 'clvm.ddns.net:8026';
    $dbuser = 'root';
    $dbpass = '';
    $dbname = 'ta_trial';
    //$conn = mysql_connect($dbhost, $dbuser, $dbpass);

    $connection = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname) or die("Error " . mysqli_error($connection));

    //fetch table rows from mysql db
    $sql = "select * from tbl_employee";
    $result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));

    //create an array
    $emparray = array();
    while($row =mysqli_fetch_assoc($result))
    {
        $emparray[] = $row;
    }

    echo json_encode($emparray);
?>
&#13;
&#13;
&#13;

检查结果确定