Reputation: 409
I'm trying to display results from a database in two columns but I can't seem to get it to work. I've seen some examples on here but they are very old and don't really follow what I'm doing. Below are the two errors I'm getting.All it outputs is the word "Array"
Notice: Undefined offset: 99 in G:\xampp\htdocs\carDirectory\listing.php on line 19
Notice: Array to string conversion in G:\xampp\htdocs\carDirectory\listing.php on line 23
<?php
include_once 'includes/dbh.inc.php';
include 'functions.php';
$sql = "SELECT * FROM roads ORDER BY roadName ASC";
$stmt = $mysqli->prepare($sql);
$stmt ->execute();
//stmt ->store_result();
//$stmt ->bind_result($roadID, $roadName, $reportingMark);
$result = $stmt->get_result();
//$mid = $result->num_rows;
$mid = ceil($result->num_rows/2);
while ($row = $result->fetch_row()) {;
$listing[] = $row;
}
for($i=0; $i<$mid; $i++){
$colOne = $listing[$i];
$colTwo = $listing[$i + $mid];//line 19
}
echo "<table>";
echo "<td>";
echo $colOne;//line 23
echo "</td>";
echo "<td>";
echo $colTwo;
echo "</td>";
echo "</table>";
//echo $data;*/
//printf("%s (%s)\n",$roadID, $roadName, $reportingMark);
$stmt->close();
$mysqli->close();
Upvotes: 0
Views: 84
Reputation: 147146
You need to output your table rows as you loop over the data. Note that since each row is an array, you need to implode
the row to output it as a string. In the code below I've assumed you want separate columns for each value in the row. You can use fetch_all
to avoid the loop over fetch_row
. Also you need to take account of the fact that you may have an odd number of rows; in that case you need to supply default data for the second column in the last row. I've done this using array_fill
to create an array of blank data. Combining all of this, replace the code after $result = $stmt->get_result();
with this:
$listing = $result->fetch_all();
$mid = ceil(count($listing) / 2);
echo "<table>\n";
for ($i = 0; $i < $mid; $i++) {
echo '<tr>';
echo '<td>' . implode('</td><td>', $listing[$i]) . '</td>';
echo '<td>' . implode('</td><td>', $listing[$i+$mid] ?? array_fill(0, count($listing[0]), '')) . '</td>';
echo "</tr>\n";
}
echo "</table>\n";
$stmt->close();
$mysqli->close();
Demo (with random sample data) on 3v4l.org
Upvotes: 1