我正在尝试使用 PhP 从 mysql 检索数据。我只是在测试我的 PHP 文件。如果这可行,那么我将开始努力将这些结果添加到我的 Android 应用程序中。
显示的 PHP 结果始终为空。我可以确认数据在数据库中可用。
DATABASE 的表名为:
population - 字段有:id, gender, city, state
结果总是:
{"成功":1,"数据":[{"id":null,"性别":null,"city":null,"state":null}]}
我不确定代码中有什么问题:
<?php
include("db_config.php");
$response = array();
$gender = 'Male';
// get a product from products table
$result = mysql_query("SELECT * FROM population WHERE gender = '$gender'");
if (!empty($result))
{
// check for empty result
if (mysql_num_rows($result) > 0)
{
$result = mysql_fetch_array($result);
$data = array();
$data ["id"] = $row["id"];
$data ["gender"] = $row["gender"];
$data ["city"] = $row["city"];
$data ["state"] = $row["state"];
// success
$response["success"] = 1;
$response["data"] = array();
array_push($response["data"], $data);
echo json_encode($response);
}
else
{
$response["success"] = 0;
$response["message"] = "No data found";
echo json_encode($response);
}
}
else
{
$response["success"] = 0;
$response["message"] = "No data found";
echo json_encode($response);
}
?>
有人可以帮我解决这个 PHP 代码吗?我过去三天一直在研究这个问题,找不到任何解决方案?
谢谢!
最佳答案
立即尝试,
if (mysql_num_rows($result) > 0)
{
$row = mysql_fetch_array($result); // wrong initialize to the result value
$data = array();
$data ["id"] = $row["id"];
$data ["gender"] = $row["gender"];
$data ["city"] = $row["city"];
$data ["state"] = $row["state"];
}
关于php - 使用 PHP 从数据库中检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15924396/