【发布时间】:2026-01-17 22:25:01
【问题描述】:
我正在关注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
谢谢
【问题讨论】:
-
mysql_query是一个过时的接口,不应在新应用程序中使用,并将在未来的 PHP 版本中删除。像PDO is not hard to learn 这样的现代替代品。如果您是 PHP 新手,PHP The Right Way 之类的指南可以帮助您解释最佳实践。 -
您是否启用了错误报告?如果是,但您仍然没有得到任何东西,请检查
json_last_error()的输出。 -
我不会相信任何推荐
mysql_connect()的 2014 年编写的网站或教程。 -
在 json_encode 之前,$json_response 的 var 转储是什么样的?
-
var_dump($json_response): array(2) { [0]=> array(6) { ["id_employee"]=> NULL ["emp_name"]=> NULL ["designation"] => NULL ["date_joined"]=> NULL ["salary"]=> NULL ["id_dept"]=> NULL } [1]=> array(6) { ["id_employee"]=> NULL ["emp_name" ]=> NULL ["designation"]=> NULL ["date_joined"]=> NULL ["salary"]=> NULL ["id_dept"]=> NULL } }