显示准备语句的结果

时间:2016-09-21 09:59:04

标签: javascript php ajax

我有下表:

| id | name  | age |
|----|-------|-----|
| 1  | Peter | 23  |
| 2  | Amie  | 34  |
| 3  | Eddy  | 45  |
| 4  | Peter | 56  |
| 5  | Eddy  | 67  |

我现在想要检索名为Peter的所有用户的年龄。

JS:

function getAge() {
    $.ajax({
        type : "POST",
        url : "backend.php",
        data : {
            q : "user",
            name : 'Peter'
        },
        success : function(data) {
            console.log(data)
            if (data.length > 0) {

            } else {
                console.log("empty")
            }
        },
        error : function(jqXHR, status, error) {
            console.log(status, error);
        }
    });
}

PHP:

if (isset ( $_POST )) {
   if ($_POST ['q'] == "user") {
        $name = $_POST ["name"];

        $stmt = $link->prepare ( "SELECT age FROM tab1 WHERE name= ?" );

        $stmt->bind_param ( "s", $name );
        $stmt->execute ();
        $stmt->store_result ();

        if ($stmt->num_rows >= 1) {
            echo "Yes"; // only this Yes is being returned
            $arr = array ();
            while ( $stmt->fetch () ) {
                $arr [] = $name;
            }
            return $arr;
        } else {
            echo "0 records found";
        }

        $link->close ();
}

而不是2356的数组,我只获得Yes

那么如何才能获得具有年龄的数组呢?

1 个答案:

答案 0 :(得分:1)

只需将此添加到您的php函数中。这意味着你想将json返回到这个页面

header('Content-Type: application/json');

将您的返回$ arr更改为echo json_encode($ arr);将数组转换为json对象也会删除回声"是&#34 ;;

echo json_encode($arr);

你的php函数看起来像这样

if (isset ( $_POST )) {
   if ($_POST ['q'] == "user") {
        header('Content-Type: application/json');
        $name = $_POST ["name"];

        $stmt = $link->prepare ( "SELECT age FROM tab1 WHERE name= ?" );

        $stmt->bind_param ( "s", $name );
        $stmt->execute ();
        $stmt->store_result ();

        if ($stmt->num_rows >= 1) {
            $arr = array ();
            while ( $stmt->fetch () ) {
                $arr [] = $name;
            }
            echo json_encode($arr);
        } else {
            echo "0 records found";
        }

        $link->close ();
    }
}