简体   繁体   中英

How to store entire mysql_fetch_array results into an array? PHP

I have one SQL query and the results are retrieved using;

$result = mysql_query($query);

And the results are printed using;

while($row = mysql_fetch_array($result)){
    echo $row['column']."<br>";
}

I want to store entire $row['column'] into an array. For that, the above code can be replaced by;

$my_array[] = "";
while($row = mysql_fetch_array($result)){
    echo $row['column']."<br>";
    $my_array[] = $row['column'];
}

But here, the while loop is executed. Is there any other efficient / better method, avoiding loops?

Store your desired value in your array right there in the first loop.

while($row = mysql_fetch_array($result)){
    echo $row['column']."<br>";
    $my_array[] = $row['column'];
}

Now you don't need 2 loops. $my_array is available to you to use anywhere you like

But here, the while loop is executed again

No, absolutely incorrect. This can be done in just 1 loop call and loop is not executed again.

But here, the while loop is executed. Is there any other efficient / better method, avoiding loops?

Nope there is none using mysql_* but yes using mysqli or pdo you can fetch all rows in an array using just one call without any loops.

How can I do that using mysqli_* can u include that in your answer

$link = mysqli_connect("localhost", "user", "password", "database");
$query = "SELECT column FROM yourTable";
$result = mysqli_query($link,$query);
$my_array = mysqli_fetch_all($result,MYSQLI_ASSOC);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM