Reputation: 21406
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?
Upvotes: 0
Views: 2331
Reputation: 46900
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);
Upvotes: 4