Jump to content

PHP while loop


sigmahokies

Recommended Posts

Hi everyone,

 

I am still learning to do PHP, please be patient with me. Thank you so much! I am trying to understand how "while loop" work in PHP, or do you recommend me use foreach, for, or do for array list from MySQL database?

 

my Code in PHP:

 

<!doctype html>
 
<html>
 
<head>
 
<title>Test foreach columns</title>
 
<link href="default.css" rel="stylesheet" type="text/css">
 
</head>
 
<body>
 
<?php
$Garydb = mysqli_connect("XXXXXX","XXXXXX","XXXXXX") or die("Could not connect MySQL Database");
 
mysqli_select_db($Garydb, "XXXXXX") or die("Could not find Database");
 
$sql = "SELECT * FROM XXXXXX";
 
$display = mysqli_query($Garydb, $sql);
 
while($key = mysqli_fetch_array($display)) 
 
{
 
echo "<table><tr><td>".$key."</td><td>".$key."</td></tr></table>";
 
}
 
?>
 
</body>
 
</html>
 
seem display on website showing "Array Array" 12 row and 2 columns, what I did do wrong?
Link to comment
https://forums.phpfreaks.com/topic/296380-php-while-loop/
Share on other sites

while() loops will loop until the condition is no longer true. In the case of mysqli results, mysqli_fetch_* functions all return false when they reach the end of the result set.

 

foreach() is for loop through arrays.

 

$key in your code is an array of the columns in the current row. You need $key[0], $key[1] etc to echo the individual fields. Or you can use field names as the key (but I don't know what they are as you use select * ). When you come back to the code in a few months you won't know what it's selecting either. Specify just the columns you want and not * .

Link to comment
https://forums.phpfreaks.com/topic/296380-php-while-loop/#findComment-1512165
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.