0

データベースからすべてのタスクを取得する php ファイルを作成しますが、ブラウザーに「localhost/evisiting/get_all_task.php」という URL を入力すると、すべてのタスクの詳細が取得されますが、各行に null データが含まれます。ただし、データベース テーブルにデータを入力します。null値ではなくデータベースからこれらの値を取得する方法を教えてください..

その私のphpファイル:

    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);
}
?>
4

1 に答える 1

1

while() ループ内で間違った変数を使用しています。$resultフェッチした行ではなく、クエリ結果ハンドルです。

        $my_task["cid"] = $result["cid"];
                          ^^^^^^^--- should be $row

同様に、単純にこれを取得できる場合でも、個々のフィールドを取得するために多くのコードを吐き出しています。

$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 配列のフィールド名を変更する必要がある場合は、クエリで単純にエイリアスを作成します。

于 2013-01-14T14:39:02.593 に答える