首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >数据库:获取null结果

问数据库:获取null结果
EN

Stack Overflow用户
提问于 2013-01-14 22:36:29
回答 1查看 102关注 0票数 0

我创建了php文件来获取数据库中的所有任务,但当我在浏览器中输入url "localhost/evisiting/ get _ all _task.php“时,它会获取所有任务的详细信息,但每一行的数据都为空。但是,我填充我的数据库表。请指导我如何从数据库中获取这些值,而不是空值。

这是我的php文件:

代码语言:javascript
复制
    get_all_task.php
<?php

/*
 * Following code will list all the tasks
 */

// array for JSON response
$response = array();

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// get all task from my_task table
$result = mysql_query("SELECT *FROM my_task") or die(mysql_error());

// check for empty result
if (mysql_num_rows($result) > 0) {
    // looping through all results
    // task node
    $response["my_task"] = array();

    while ($row = mysql_fetch_array($result)) {
        // temp user array
            $my_task = array();
            $my_task["cid"] = $result["cid"];
            $my_task["cus_name"] = $result["cus_name"];
            $my_task["contact_number"] = $result["contact_number"];
            $my_task["ticket_no"] = $result["ticket_no"];
            $my_task["task_detail"] = $result["task_detail"];

        // push single task into final response array
        array_push($response["my_task"], $my_task);
    }
    // success
    $response["success"] = 1;

    // echoing JSON response
    echo json_encode($response);
} else {
    // no task found
    $response["success"] = 0;
    $response["message"] = "No task found";

    // echo no users JSON
    echo json_encode($response);
}
?>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-01-14 22:39:03

您在while()循环中使用了错误的变量。$result是您的查询结果句柄,而不是您获取的行:

代码语言:javascript
复制
        $my_task["cid"] = $result["cid"];
                          ^^^^^^^--- should be $row

同样,您需要编写大量代码来获取单个字段,而您可以简单地使用以下代码:

代码语言:javascript
复制
$result = mysql_query("SELECT cid, cus_name, contact_number, .... FROM my_task") or die(mysql_error());
$response['my_task'] = array();
while($row = mysql_fetch_assoc($result)) {
   $response['my_task'][] = $row;
}

最终结果完全相同,但所有这些字段名称的重复要少得多-如果您想要在此结果中添加一个新字段,只需将其添加到SELECT语句中,其余代码将自动处理它。如果需要更改$response数组中的字段名称,只需在查询中为其设置别名。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14320474

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档