php - 使用 PHP 从数据库中检索数据

标签 php mysql

我正在尝试使用 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/

相关文章:

php - FOSUserBundle 和 REST Api 调用 : How to use custom FormType?

php - 用 preg_replace_callback 替换 preg_replace() e 修饰符

javascript - 将 div 替换为另一个 if 语句

php - mysqli fetch_assoc() 未发布

mysql - 如何连接flutter到localhost mysql数据库

php - 使用php上传文件时获取文件大小

php - 直接从Google Drive上传到亚马逊S3

php - HTML 和 Javascript 中的多步选择框

mysql - 恢复 MYSQL 数据库时出错

mysql - mysql 是如何工作的?