'Mysqli Output to a table
So my goal is to output some mysql info to a table. I want it to start a new column every 18th record. Here is my current code:
$hostname = "localhost"; //SET SERVER/HOSTNAME
$dbusername = "username"; //SET DATABASE USERNAME
$dbname = "database"; //SET DATABASE NAME
$dbpassword = "password"; //SET DATABASE USERNAME
$link = mysqli_connect($hostname, $dbusername, $dbpassword, $dbname);
if (!$link)
{
die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
}
$continent='Africa';
//GET AFRICA Countries
$sql = "SELECT country FROM countries WHERE continent = '$continent';";
$result = mysqli_query($link, $sql, MYSQLI_USE_RESULT);
if (!result)
{
echo 'Error: ', $mysqli->error;
}
while($row = $result->fetch_assoc()){
$country = $row['country'];
echo "$country<br>";
}
Right now it just outputs the list in a straight column, but I want it to start a new column after x amount of times. Is that possible to do?
Solution 1:[1]
As discussed in comments it can be done but it is easier to start a new row after x amount of times.
- count total rows using
$result->num_rows
- calculate columns by dividing total rows by required rows
- display required columns using table
- use modulus operator to generate new row if
$i % $columns ==0
TRY
$requiredRows= 18;
$rows = $result->num_rows ;
$columns = ceil($rows/$requiredRows);
$i = 0;
while($row = $result->fetch_assoc())
{
if ($i == 0) {
echo "<table><tr><td>";
}
elseif ($i % $columns) {// <> 0
echo "</td>\n";
echo "<td>\n";
}else{//$i % $columns == 0
echo "</td>\n";
echo "</tr>\n";
echo "<tr>\n";
echo "<td>\n";
}
echo $row['country'];
$i++;
}
You can also hard code column number if required.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |