在单个数组中返回多个SELECT查询

nov*_*int 3 php mysql select http angularjs

我正在编写angularjs应用程序,它依赖于从MySQL数据库返回的数据.

Angularjs代码发出HTTP请求并将返回的数据记录到控制台:

$http({method: 'POST', url: 'php/return_something.php', headers: {'Content-Type': 'application/json'}})
    .success(function(data, status, headers, config) {
    //The API call to the back-end was successful (i.e. a valid session)
        console.log(data);
    })
    .error(function(data, status, headers, config) {
        console.log("Error.");
    });
Run Code Online (Sandbox Code Playgroud)

return_something.php

try
{
    $conn = new PDO("mysql:host=".DB_HOST."; dbname=".DB_DATABASE, DB_USER, DB_PASSWORD);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = $conn->prepare("SELECT count(id_table_x) from table_x; SELECT count(id_table_y) from table_y;");
    $sql->execute();

    // set the resulting array to associative
    $results = $sql->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($results);
}

catch(PDOException $e)
{
    echo $sql . "<br />" . $e->getMessage();
}

$conn = null;
Run Code Online (Sandbox Code Playgroud)

对于控制台,将记录包含一个元素的数组.

[宾语]

在此对象内部存在第一个查询的结果("table_x中的SELECT count(id_table_x)").

我应该改变什么,我会看到第二个查询的结果("table_y中的SELECT count(id_table_y)")作为这个数组的第二个元素?任何帮助赞赏.

luk*_*app 5

您可以编写两个查询,这些查询也更具可读性(imho):

$sql = $conn->prepare("SELECT count(id_table_x) from table_x;");
$sql->execute();

$sql2 = $conn->prepare("SELECT count(id_table_y) from table_y;");
$sql2->execute();

$results[] = $sql->fetchAll(PDO::FETCH_ASSOC);
$results[] = $sql2->fetchAll(PDO::FETCH_ASSOC);
Run Code Online (Sandbox Code Playgroud)

编辑: $results[] =是一个快捷方式$results.push().之前,您必须将$ results定义为一个数组:

$results = array(); 
Run Code Online (Sandbox Code Playgroud)