I use the code below to display 50 US states from MySQL db in a single row separated by “|”. I need help displaying 50 states in 20 rows by 3 columns table in alphabetical order (1st column to have states 1-20, 2nd 21-40, 3rd 41-50)
$result=mysql_db_query($dbname,"select `state` from states order by `state`");
while(list($name)=mysql_fetch_array($result)){
echo "<a href=\\"?state=$name\\" >$name</a> | \
" ;
}
If you are using the table simply to hold the display, the countries could be UL or P separated couldnt they?
If so, then just do this, create a simpler table.
$array = range(1,52); // this is pretending to your result from the db
$cols = 3; // decide how many cells you want, wide
$rows = ceil( count($array) / $cols ); // works out how many rows
$cnt = 1; // set a counter for upcoming loop
echo '<table><tr valign=top><td>' . PHP_EOL; // start table
foreach ($array as $name){
if( $cnt >= $rows ) { // start a new TD when you get to the number of rows
echo '<p>' . $name . '</p></td><td>' .PHP_EOL ;
$cnt = 0; // reset the counter, and start a new column
}else{ // other wise just echo the country name
echo '<p>' . $name . '</p>' . PHP_EOL;
}
$cnt++;
}
echo '</td></tr></table>' . PHP_EOL;
Makes a table with 3 td’s each holding 18 countries (52 / 3 and rounded up)
I commented it so you can hopefully see what is going on, and you should be able to spot where the A links go, or how to turn the Ps into UL / LI s.
function get_states() {
//get stuff in the cart and return in indexed array
$q1 = "SELECT id, state FROM states ";
$incart_r = mysql_query($q1) or die(mysql_error());
$contents = array();
while($incart = mysql_fetch_array($incart_r)){
//build array of info
$item = array(
$incart['id'],
$incart['state']);
array_push($contents,$item);
}
return $contents ;
}
$c = get_states();
$cols = 3; // decide how many cells you want, wide
$rows = ceil( count($c) / $cols ); // works out how many rows
$cnt = 1; // set a counter for upcoming loop
echo '<table><tr valign=top><td>' . PHP_EOL; // start table
//foreach ($array as $name){
for($i=0; $i < count($c); $i++){
if( $cnt >= $rows ) { // start a new TD when you get to the number of rows
echo "<p><a href='?stateID=" . $c[$i][0] . "'>" . $c[$i][1] . "</a></p></td><td>" .PHP_EOL ;
$cnt = 0; // reset the counter, and start a new column
}else{ // other wise just echo the country name
echo "<p><a href='?stateID=" . $c[$i][0] . "'>" . $c[$i][1] . "</a></p>" . PHP_EOL;
}
$cnt++;
}
echo '</td></tr></table>' . PHP_EOL;