如何在PHP的while循环之外获取所有数组值?

时间:2018-09-30 08:42:37

标签: php mysql

我知道这个问题已经问过很多次了,但是给出的解决方案似乎都不适合我。使用while循环,我从数据库中检索多个值作为数组。之后-在while循环之外(!important)-,我需要检查此数组中是否存在特定值。

<?php
$require "db.php";

$sql = "SELECT id FROM users WHERE email='" . $user . "';";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    $row = mysqli_fetch_assoc($result);
    $userId = $row["id"];

    $sql = "SELECT item_id FROM saves WHERE user_id='" . $userId . "';";
    $result = mysqli_query($conn, $sql);

    if (mysqli_num_rows($result) > 0) {
        while ($row = mysqli_fetch_assoc($result)) {
            $saved = $row["item_id"];
        }
    } else {
        echo "Error.";
    }
} else {
    echo "Error.";
}

print_r($saved);

如果您想知道,$user等于John,而$userId等于1

如您所见,$saved变量假设包含我的item_id数据库表中saves为{{1 }}。

这是我的user_id数据库表上的内容:

$userId

所以saves数组应该包含值<table border="1"> <tr> <td> user_id </td> <td> item_id </td> </tr> <tr> <td> 1 </td> <td> 1 </td> </tr> <tr> <td> 2 </td> <td> 1 </td> </tr> <tr> <td> 1 </td> <td> 2 </td> </tr> </table>$saved,对吧?

问题是,当我1 2在while循环之外时,它仅输出最后一个条目(print_r)。

如何在while循环之外获取$saved数组的所有值?

4 个答案:

答案 0 :(得分:2)

$saved循环开始之前,您首先需要将while变量初始化为一个空数组。

$saved = array();

现在,在while循环中,您没有将$saved用作数组,而是将其用作普通变量。每次在您的while循环中,它都会被覆盖。

请执行以下操作:

$saved[] = $row["item_id"];

注意使用[]。基本上,它将新条目推入$saved数组中。另一种选择是array_push函数。例如:

$push_result = array_push($saved, $row["item_id"]);

这就是应该的样子:

$require "db.php";

$sql = "SELECT id FROM users WHERE email='" . $user . "';";
$result = mysqli_query($conn, $sql);

// initialize $saved here
$saved = array();

if (mysqli_num_rows($result) > 0) {
    $row = mysqli_fetch_assoc($result);
    $userId = $row["id"];

    $sql = "SELECT item_id FROM saves WHERE user_id='" . $userId . "';";
    $result = mysqli_query($conn, $sql);
    //$saved = []; - no need of this now
    if (mysqli_num_rows($result) > 0) {
        while ($row = mysqli_fetch_assoc($result)) {
            $saved[] = $row["item_id"]; // you are missing []
        }
    } else {
        echo "Error.";
    }
} else {
    echo "Error.";
}

print_r($saved);

最重要的,您的查询对SQL injection related issues开放。请仔细阅读how to use Prepared Statements,并改用它们。

答案 1 :(得分:1)

基于此代码

if ("geolocation" in navigator) {
  /* geolocation is available */
  navigator.geolocation.getCurrentPosition(displayLocationInfo);
  
  function displayLocationInfo(position) {
    const lng = position.coords.longitude;
    const lat = position.coords.latitude;

    console.log(`longitude: ${ lng } | latitude: ${ lat }`);
  }
} else {
  /* geolocation IS NOT available  */
  console.log('geolocation IS NOT available on your browser');
}

while ($row = mysqli_fetch_assoc($result)) { $saved = $row["item_id"]; } 将始终包含$saved中的最后一个值,因为您将$row['item_id']视为变量而不是数组 < / p>

如果没记错的话,请调整您的代码,使其像这样

$saved

应该给您想要的结果。

答案 2 :(得分:0)

首先创建一个空数组,并将所有值附加到while循环内。

$require "db.php";

$sql = "SELECT id FROM users WHERE email='" . $user . "';";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    $row = mysqli_fetch_assoc($result);
    $userId = $row["id"];

    $sql = "SELECT item_id FROM saves WHERE user_id='" . $userId . "';";
    $result = mysqli_query($conn, $sql);
     $saved = [];
    if (mysqli_num_rows($result) > 0) {
        while ($row = mysqli_fetch_assoc($result)) {
            $saved = $row["item_id"];
        }
    } else {
        echo "Error.";
    }
} else {
    echo "Error.";
}

print_r($saved);

答案 3 :(得分:0)

首先声明$ saved = [];在检查数字行之前。因此,如果查询不返回任何记录,则可以抑制未定义的变量$ saved。

然后在while循环下使用$ saved [] = $ row [“ item_id”];

   <?php
    $require "db.php";

    $sql = "SELECT id FROM users WHERE email='" . $user . "';";
    $result = mysqli_query($conn, $sql);   

     $saved = [];
        if (mysqli_num_rows($result) > 0) {
            $row = mysqli_fetch_assoc($result);
            $userId = $row["id"];

            $sql = "SELECT item_id FROM saves WHERE user_id='" . $userId . "';";
            $result = mysqli_query($conn, $sql);

            if (mysqli_num_rows($result) > 0) {
                while ($row = mysqli_fetch_assoc($result)) {
                    $saved[] = $row["item_id"];
                }
            } else {
                echo "Error.";
            }
        } else {
            echo "Error.";
        }