在JSON中获取NULL

时间:2014-05-13 15:26:28

标签: php mysql sql json

我跟随此website创建mySQL表和php以便将数据转换为JSON

SQL:

  CREATE TABLE IF NOT EXISTS `employee` (
  `id_employee` int(3) unsigned NOT NULL AUTO_INCREMENT,
  `emp_name` varchar(10) DEFAULT NULL,
  `designation` varchar(9) DEFAULT NULL,
  `date_joined` date DEFAULT NULL,
  `salary` decimal(7,2) DEFAULT NULL,
  `id_dept` int(2) DEFAULT NULL,
  PRIMARY KEY (`id_employee`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=11 ;


INSERT INTO `employee` (`id_employee`, `emp_name`, `designation`, `date_joined`, `salary`, `id_dept`) VALUES
(1, 'SMITH', 'CLERK', '2010-12-17', 2500.00, 20),
(2, 'ALLEN', 'SALESMAN', '2005-02-20', 3500.00, 30),
(3, 'WARD', 'SALESMAN', '2009-02-22', 3550.00, 30),
(4, 'JONES', 'MANAGER', '2010-04-02', 3975.00, 20),
(5, 'MARTIN', 'SALESMAN', '2011-09-28', 3300.00, 30);

PHP:

<?php
//Create Database connection
$db = mysql_connect("localhost","root","root");
if (!$db) {
    die('Could not connect to db: ' . mysql_error());
}

//Select the Database
mysql_select_db("test_json",$db);

//Replace * in the query with the column names.
$result = mysql_query("select * from employee", $db);  

//Create an array
$json_response = array();

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $row_array['id_employee'] = $row['id_employee'];
    $row_array['emp_name'] = $row['emp_name'];
    $row_array['designation'] = $row['designation'];
    $row_array['date_joined'] = $row['date_joined'];
    $row_array['salary'] = $row['salary'];
    $row_array['id_dept'] = $row['id_dept'];

    //push the values in the array
    array_push($json_response,$row_array);
}
echo json_encode($json_response);

//Close the database connection
fclose($db);

?>

但是,我得到2个结果为null,没有其他错误:

[{"id_employee":null,"emp_name":null,"designation":null,"date_joined":null,"salary":null,"id_dept":null},{"id_employee":null,"emp_name":null,"designation":null,"date_joined":null,"salary":null,"id_dept":null}]

我刚刚复制了代码并尝试运行它,结果怎么回事?

有人可以指出我的代码有什么问题吗?

或者这是我的服务器问题??

PHP版本:5.2

MySQL版。 :5.1

谢谢

2 个答案:

答案 0 :(得分:0)

请查看mysql_set_charset()。至于JSON本身,可以使用json_last_error()获取上一个错误。

答案 1 :(得分:0)

您应该将mysql_fetch_array替换为mysql_fetch_assoc,以便按列名访问变量。

另外,你应该开始使用mysqli而不是mysql来连接和交换来自php的mysql数据库。