Jump to content
sigmahokies

PHP while loop

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?

Share this post


Link to post
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 * .

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


×
×
  • 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.