在单个数组

时间:2015-08-06 12:57:24

标签: php mysql angularjs http select

我正在编写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.");
    });

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;

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

  

[对象]

在此对象内部有第一个查询的结果(&#34;来自table_x&#34; 的SELECT count(id_table_x))。

我应该更改哪些内容,我会看到第二个查询(&#34; SELECT count(id_table_y)from table_y&#34; )的结果作为此数组的第二个元素?任何帮助表示赞赏。

2 个答案:

答案 0 :(得分: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);

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

$results = array(); 

答案 1 :(得分:2)

您不能在一个查询中创建多个SELECT语句。 另一种方式:

SELECT count(id_table_x) from table_x UNION SELECT count(id_table_y) from table_y;

OR

SELECT "table_x" as tableName, count(id_table_x) as nbID from table_x UNION SELECT "table_y" as tableName, count(id_table_y) as nbID from table_y;

您将获得这些数据

tableName | nbID
==========|======
table_x   | 6
table_y   | 1

完整代码:

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 "table_x" as tableName, count(id_table_x) as nbID from table_x UNION SELECT "table_y" as tableName, count(id_table_y) as nbID from table_y;');
    $sql->execute();

    // set the resulting array to associative
    $results = $sql->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($results);
    /*
        [
            {'tableName':'table_x', 'nbID': 6},
            {'tableName':'table_y', 'nbID': 42}
        ]
    */
}catch(PDOException $e){
    echo $sql . "<br />" . $e->getMessage();
}

$conn = null;