Page 1 of 1

Loop through a table. PHP.

Posted: Sat Nov 27, 2010 9:38 pm
by rockinliam
How would i loop through a table and the to print out all the fields into a table and then stop when the end of the table is reached?

Re: Loop through a table. PHP.

Posted: Sat Nov 27, 2010 10:54 pm
by Jackolantern
When you say "loop" through a table, you mean a MySQL table, correct? If so, here is a simple script that may help show you how to iterate through a multiple-result MySQL query. This was just a test where I made a dummy db table, and made several entries with a "mobid" of 3. I was able to iterate through the results and print them out in a table.

Code: Select all

<html>
<head>
	<style type="text/css">
		table {
			padding=5px;
		}
	</style>
</head>
<body>

<?php

include 'connect.php';
session_start();

echo "Start of script";

$query = "SELECT * FROM multitest WHERE mobid='3'";
?>

<table border="3" cellpadding="3" cellspacing="0">

<?php
if ($result = mysqli_query($db, $query)) {
	//fetch assoc array, and iterate through all of the results
	//$row is going to be an INDEXED array, not an ASSOCIATIVE array, so all
	//offsets are number indexes, not the names of the columns in the db.
	while ($row = mysqli_fetch_row($result)) {
		?>
		<tr>
			<td>ID:</td>
			<td><?php echo($row[0]); ?> </td>
		</tr>
		<tr>
			<td>Mob ID:</td>
			<td><?php echo($row[1]); ?> </td>
		</tr>
		<tr>
			<td>Name:</td>
			<td><?php echo($row[2]); ?> </td>
		</tr>
		<tr>
			<td>Address:</td>
			<td><?php echo($row[3]); ?> </td>
		</tr>
		<tr>
			<td>Class:</td>
			<td><?php echo($row[4]); ?> </td>
		</tr>
		
		<?php		
	}
	
	mysqli_free_result($result);
}

mysqli_close($db);

?>

</table>

</body>
</html>

Re: Loop through a table. PHP.

Posted: Sat Nov 27, 2010 11:00 pm
by Callan S.
You mean go through the database? I'm not sure it's what you want, but in a highscore code I found once, it used something like

Code: Select all

$playerinfo  = "SELECT name, score FROM players";
$playerinfo2 = mysql_query($playerinfo);

while($playerinfo3 = mysql_fetch_array($playerinfo2))
{
// do yo thang har!
}

Re: Loop through a table. PHP.

Posted: Sat Nov 27, 2010 11:42 pm
by rockinliam
@Jack - Thanks, you got me out of a hole.