gpt4 book ai didi

php - 如何在执行多个查询时返回多个结果?

转载 作者:行者123 更新时间:2023-11-29 10:27:29 24 4
gpt4 key购买 nike

我正在一个函数内执行 4 个查询。如何一次返回这 4 个结果,以便在调用函数时可以使用所有 4 个结果?我应该创建一个数组并将所有结果存储在该数组中吗?我尝试一一返回结果,但在调用 return 命令后,函数从该点退出。有没有办法单独返回每个查询结果?这是我的代码:

function select_all_category_name() {
require 'admin/db_connect.php';
$sql="SELECT * FROM tbl_category WHERE publication_status=1 AND deletion_status=1";

if (mysqli_query($db_connect, $sql)) {

$sql1="SELECT * FROM tbl_category WHERE publication_status=1 AND deletion_status=1 AND mpid='' AND spid='' AND pid=''";
$sql2="SELECT * FROM tbl_category WHERE publication_status=1 AND deletion_status=1 AND mpid!='' AND spid='' AND pid=''";
$sql3="SELECT * FROM tbl_category WHERE publication_status=1 AND deletion_status=1 AND mpid!='' AND spid!='' AND pid=''";
$sql4="SELECT * FROM tbl_category WHERE publication_status=1 AND deletion_status=1 AND mpid!='' AND spid!='' AND pid!=''";
$query_result1=mysqli_query($db_connect, $sql1);
$query_result2=mysqli_query($db_connect, $sql2);
$query_result3=mysqli_query($db_connect, $sql3);
$query_result4=mysqli_query($db_connect, $sql4);


} else {
die("Query Problem". mysqli_error($db_connect));
}
}

db_connect.php 文件包含连接。

最佳答案

使用数组:

function select_all_category_name() {
require 'admin/db_connect.php';
$sql="SELECT * FROM tbl_category WHERE publication_status=1 AND deletion_status=1";

if (mysqli_query($db_connect, $sql)) {
$ret = [
"{$sql} AND mpid ='' AND spid ='' AND pid =''",
"{$sql} AND mpid!='' AND spid ='' AND pid =''",
"{$sql} AND mpid!='' AND spid!='' AND pid =''",
"{$sql} AND mpid!='' AND spid!='' AND pid!=''",
];
foreach ($ret as $i => $sqlx) {
$ret[$i] = mysqli_query($db_connect, $sqlx);
};
return $ret;
}
return false;
}

或者您可以对整个函数使用单个查询(如果没有找到任何内容,它将返回一个空数组):

SELECT
CASE
WHEN mpid='' AND spid='' AND pid='' THEN 0,
WHEN mpid!='' AND spid='' AND pid='' THEN 1,
WHEN mpid!='' AND spid!='' AND pid='' THEN 2,
WHEN mpid!='' AND spid!='' AND pid!='' THEN 3
ELSE -1
END AS idx,
*
FROM tbl_category
WHERE publication_status=1 AND deletion_status=1
HAVING idx != -1

关于php - 如何在执行多个查询时返回多个结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48034329/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com