php - 在多个数组中循环多个 SQL 查询

标签 php mysql sql arrays

我是 PHP 初学者。我以前涉足过,但当我开始掌握诀窍时,一个新项目将我带到了其他地方。如果有人可以提供帮助;我会很感激。

我正在使用多个查询和数组来检索两个 mySQL 表之间的数据,从 1 个初始已知变体开始。

我希望每个查询都能处理上一个查询的所有结果。这并没有发生。

当前结果:第一个查询回显所有结果。第二个查询回显一个结果。第三个查询回显 1 个结果。最终回显显示所有最终结果(所需的,但缺少前 148 行)。

期望的结果:回显所有三个查询的所有 149 个结果,然后回显所有 3 个查询的表/数组(以确认相关性)。

<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
//Select all POST_IDs for variation 2.1M
$sql = "SELECT post_id FROM wp_postmeta WHERE meta_value = '2-1m'";
$result = $conn->query($sql);
//Array and display POST_IDs
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["post_id"]. "<br>";
}
} else {
    echo "0 results";
}
//Prepare POST_IDs for next query
foreach ($result as $row){
$postids = $row["post_id"];
    }
        //Use POST_IDs to select all PARENT_IDs
    $sql2 = "SELECT post_parent FROM wp_posts WHERE ID = ($postids)";
$result2 = $conn->query($sql2);
//Array and display PARENT_IDs
if ($result2->num_rows > 0) {
    // output data of each row
    while($row2 = $result2->fetch_assoc()) {
        echo "parentid: " . $row2["post_parent"]. "<br>";
    }
} else {
    echo "0 results";
}
//Prepare PARENT_IDs for next query
foreach ($result2 as $row2){
$parentids = $row2["post_parent"];
}
//Select PRICES using PARENT_IDs and META_KEY for Price
$sql3 = "SELECT meta_value FROM wp_postmeta WHERE meta_key = '_price' AND post_id = ($parentids)";
$result3 = $conn->query($sql3);
if ($result3->num_rows > 0) {
    // output data of each row
    while($row3 = $result3->fetch_assoc()) {
        echo "price: " . $row3["meta_value"]. "<br>";
    }
} else {
    echo "0 results";
}
//Array and display PRICES
foreach ($result3 as $row3){
$prices = $row3["meta_value"];
}
//Display all retrieved data
echo "<div><p>" . $postids . " " . $parentids . " " . $prices . "</p></div>";
$conn->close();
?>

最佳答案

您正在覆盖变量而不是将它们累积到数组中:

foreach ($result as $row){
    $postids = $row["post_id"];
}

应该是:

$postids = [];
foreach ($result as $row){
    $postids[] = $row["post_id"];
}

然后:

"WHERE ID = ($postids)"

应该是:

if (!empty($postids)) {
 ... "...WHERE ID IN (".implode(',', $postids).")..." ...
}

注意:您应该看看参数化查询:Parameterized Queries PHP/MySQL

同样的事情也发生在 $parentids 上。

关于php - 在多个数组中循环多个 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48645610/

相关文章:

php - 第 2 行第 1 列错误 : Extra content at the end of the document in PHP public function

php - 需要帮助让我的 ForEach 查询正常工作

mysql - SQL 非常简单的嵌套查询

PHP - 未找到记录

mysql - 为什么 SQL 不能在一个语句中添加和检索

sql - 从 SQL Server 创建 zip 文件

php - Paypal Checkout 客户端集成对浏览器安全吗?

php - 将数据数组从 PHP 发送到 JavaScript

php - 无法从SQLite读取Blob数据

sql - 如何在不下载工作簿的情况下在服务器上查看 Tableau 自定义 SQL?