Forum Moderators: coopster

Message Too Old, No Replies

automatically add column

automatically add new column in php array

         

daneosporin

12:12 am on Jun 8, 2005 (gmt 0)

10+ Year Member



I have a list of names being displayed, that currently use this basic code:


<table border="1">

<?php
$result = mysql_query("SELECT * FROM people");

if (!$result) {
echo("<P>Error performing query: " .
mysql_error() . "</P>");
exit();
}

while ( $row = mysql_fetch_array($result) ) {
echo("<tr><td>" . $row["first"] . $row["last"] . "</td></tr>");
}

?>
</table>

How could I get a second column automatically added when the list is larger?

electricocean

12:22 am on Jun 8, 2005 (gmt 0)

10+ Year Member



you can try a for statement
electricocean

electricocean

12:55 am on Jun 8, 2005 (gmt 0)

10+ Year Member



maybe something like this:


$num_rows = mysql_num_rows($result);
for($p = 1; $p<=$num_rows; $p++){
echo("<tr><td>" . $row["first"] . $row["last"] . "</td></tr>");
}

electricocean

mcibor

7:00 am on Jun 8, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You can change the query to mysql_fetch_assoc and do foreach. but then you would have to correct your sql query to select only things that you want:

$result = mysql_query("SELECT first, last FROM people");
...
while ($row = mysql_fetch_assoc($result)) {
echo "<tr><td>";
foreach($row as $value) echo $value;
echo "</td></tr>";
}

Or you can use the code based on what electricocean wrote:

while ($row = mysql_fetch_array($result)) {
echo "<tr><td>";
for($p = 0; $p < 2; $p++) echo $row[$p];
echo "</td></tr>";
}

However here you must also be concieus that you are selecting correct answers.
mysql_fetch_array gives you results that are both numbered and associated as well.
Best regards
Michal Cibor

And welcome to WebmasterWorld!