Php 在单个数组中返回多个SELECT查询
我正在编写angularjs应用程序,它依赖于从MySQL数据库返回的数据 Angularjs代码发出HTTP请求并将返回的数据记录到控制台:Php 在单个数组中返回多个SELECT查询,php,mysql,angularjs,http,select,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
$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\u something.php
对于控制台,将记录一个包含一个元素的数组
[对象]
在这个对象中,有一个第一次查询的结果,从table_x中选择countid_table_x
我应该改变什么,以便看到第二个查询的结果从表中选择countid\u table\u y作为该数组的第二个元素?非常感谢您的帮助。您不能在一个查询中生成多个SELECT语句。 另一种方式:
SELECT count(id_table_x) from table_x UNION SELECT count(id_table_y) 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;
您可以编写两个查询,这两个查询的可读性也更高:
$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();
AFAIK PDO不支持在单个已准备语句中进行多个查询。
$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 = array();