Display query result in a table - php

I have a MySQL query with over 50 return results. Now I need to display the results in a table with 3 rows and 3 columns.
Something like this:
<table>
<tr>
<td>Content</td>
<td>Content</td>
<td>Content</td>
</tr>
<tr>
<td>Content</td>
<td>Content</td>
<td>Content</td>
</tr>
<tr>
<td>Content</td>
<td>Content</td>
<td>Content</td>
</tr>
</table>
I tried it with PHP like this:
$q = "SELECT name, address, content FROM mytable";
$r = mysqli_query($dbc, $q);
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
$name = $row['name'];
$address = $row['address'];
$content = $row['content'];
//Create new output
$output = "<p>$name</p>";
$output .= "<p>$address</p>";
$output .= "<p>$content</p>";
//Add output to array
$mycontent[] = $output;
}
Then I am printing the content array in my table like this:
<tr>
<td><?php echo $mycontent[0]; ?></td>
<td><?php echo $mycontent[1]; ?></td>
<td><?php echo $mycontent[2]; ?></td>
</tr>
<tr>
<td><?php echo $mycontent[3]; ?></td>
<td><?php echo $mycontent[4]; ?></td>
<td><?php echo $mycontent[5]; ?></td>
</tr>
<tr>
<td><?php echo $mycontent[6]; ?></td>
<td><?php echo $mycontent[7]; ?></td>
<td><?php echo $mycontent[8]; ?></td>
</tr>
Using this code, I can only display 9 contents. My problem is that I want to display more content. I'm going to use pagination to display contents; something like 0-9, 10-18, 19-27 etc.
NOTE: I can do the pagination part.
I hope someone will give me the right direction for this.
Thank you.

try something like:
echo "<table>";
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
$name = $row['name'];
$address = $row['address'];
$content = $row['content'];
echo "<tr><td>".$name."</td><td>".$address."</td><td>".$content."</td></tr>";
}
echo "</table>";
this example will print in table all the result of the query.
if you want to limit only to some results, so limit the sql query.
for example:
$q = "SELECT name, address, content FROM mytable limit 50";
to get each content,name, address in TD, and 3 of mycontent(content, name, address) in a TR try this:
$c= mysql_query("select COUNT(name) from mytable");
$n=mysql_fetch_array($c);
$maxname= $n[0];
$i=0;
$tr=0;
echo "<table>";
while ($tr < $maxname)
{
echo "<tr>";
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC) and $i<$tr) {
$name = $row['name'];
$address = $row['address'];
$content = $row['content'];
echo "<td>".$name." | ".$address." | ".$content."</td>";
$i++;
}
echo "</tr>";
$tr= $tr+3;
}
echo "</table>";

Try something like this. It places your values in an easy to use associative array. Then you just loop through.
<?php
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
$values[] = array(
'name' => $row['name'],
'address' => $row['address'],
'content' => $row['content']
);
}
?>
<table>
<?php
foreach($values as $v){
echo '
<tr>
<td>'.$v['name'].'</td>
<td>'.$v['address'].'</td>
<td>'.$v['content'].'</td>
</tr>
';
}
?>
</table>

You can store in a variable if u r planning to use it in a function or you can just print it. Either way...
$q = "SELECT name, address, content FROM mytable";
$r = mysqli_query($dbc, $q);
$str = "<table>";
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
$str .= "<tr>";
$str .= "<td>" . $row['name'] . "</td>";
$str .= "<td>" . $row['address'] . "</td>";
$str .= "<td>" . $row['content'] . "</td>";
$str .= "</tr>";
}
$str .= "</table>"
echo $str;
There you go!

use a for-loop to iterate your $mycontent-array:
EDIT: I was made aware that $mycontent is built differently than I first assumed:
$h = "<table>"; // we are going to build the table in $h
$maxcount = count($mycontent); // get the number of values within the array
for ($i = 0;$i < $maxcount;$i++) { // counting $i up from 0 to $maxcount -1 ...
$h.= "<tr><td>{$mycontent[$i]}</td></tr>"; // build row
}
$h.= "</table>"; // close the table
echo $h; // echo it
---> live demo: http://3v4l.org/g1E1T

YOU CAN REFERENCE THIS CODE
<tbody>
<!-- <tr>
<td>Technology</td>
<td>Professor Abiola</td>
<td>wetech#school.com</td>
<td> Plot 2, Oriola road,</td>
<td>
<button type="button" class="btn btn-primary"> Edit</button>
<button type="button" class="btn btn-success">Update</button>
<button type="button" class="btn btn-danger">Delete</button>
</td>
</tr> -->
<?php
while($rows = mysqli_fetch_array($response)){
$faculty = $rows['faculty'];
$hod = $rows['hod'];
$email = $rows['email'];
// $location = $rows['location'];
echo "<tr>
<td>$faculty</td>
<td>$hod</td>
<td>$email</td>
<td>".$rows["location"]."</td>
<td>
<button type='button' class='btn btn-primary'>Edit</button>
<button type='button' class='btn btn-success'>Update</button>
<button type='button' class='btn btn-danger'>Delete</button>
</td>
</tr>";
}
?>
</tbody>
</table>

Related

PHP - Rating 1-5 in stars

<table>
<tr>
<th>name</th>
<th>startDate</th>
<th>rating</th>
<th>underlay</th>
<th>edges</th>
<th>grip</th>
<th>depth</th>
<th>length</th>
<th>height</th>
<th>realname</th>
</tr>
<?php
if(isset($_GET['DS'])){
$query='SELECT * FROM KundDetaljer where rspName = :DS';
$stmt = $pdo->prepare($query);
$stmt->bindParam(':DS', $_GET['DS']);
$stmt->execute();
foreach($stmt as $key => $row){
echo '<tr>';
echo "<td>".$row['rspName']."</td>";
echo "<td>".$row['startDate']."</td>";
echo "<td>".$row['rating']."</td>";
echo "<td>".$row['underlay']."</td>";
echo "<td>".$row['edges']."</td>";
echo "<td>".$row['grip']."</td>";
echo "<td>".$row['depth']."</td>";
echo "<td>".$row['length']."</td>";
echo "<td>".$row['height']."</td>";
echo "<td>".$row['realname']."</td>";
echo "</tr>";
}
}
echo "</table>";
?>
Hi, i'm a student in Sweden who is having a problem with making numbers to stars out of rating. The code above is the code that shows the rating from customers. When the comments from customers is made i want it to be showed as stars.
inside foreach (before any echo):
$stars = "";
for($i=0;$i<$row["rating"];$i++){
$stars .= "★";
}
Then instead of
echo "<td>".$row['rating']."</td>";
use
echo "<td>".$stars."</td>";

How to Not display empty rows?

My question is:
If you look at where it would display "
<td>1ST<?php echo $first ?></td>
"
How do I ensure that if the row associate to variable '$first' or all the others if they are empty nothing shows. Also that the '1st' doesn't show?
Have tried various things I am stumped on this!
<h2><?php echo $show_title ?></h2>
<h4>Show Date: <span class="glyphicon glyphicon-time"> </span><?php echo $show_date ?></h4>
<hr>
</a>
<hr>
<?php
// SO UPDATE THE QUERY TO ONLY PULL THAT SHOW'S DOGS
$query = "SELECT * FROM result
WHERE first IS NOT NULL";
$result = mysqli_query($connection, $query) or trigger_error
("Query Failed! SQL: $query - Error: ". mysqli_error
($connection), E_USER_ERROR);
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
$dog_name = $row['dog_name'];
$placement = $row['placement'];
$class_name = $row['class_name'];
$entries = $row['entries'];
$absentee = $row['absentee'];
$entries = $row['entries'];
$first = $row['first'];
$second = $row['second'];
$third = $row['third'];
$RES = $row['RES'];
$VHC = $row['VHC'];
$DCC = $row['DCC'];
$RDCC = $row['RDCC'];
$BCC = $row['BCC'];
$RBCC = $row['RBCC'];
$BOB = $row['BOB'];
$BP = $row['BP'];
$BJ = $row['BJ'];
?>
<table class="table" border="0"></div>
<tr>
<td><strong><?php echo $class_name ?></strong> - <h6>Entries: <?php echo $entries ?> Absentees: <?php echo $absentee ?></h6></td>
<td></td>
</tr>
<tr>
<td>DCC</td>
<td><?php echo $DCC ?></td>
</tr>
<tr>
<td>RDCC</td>
<td><?php echo $RDCC ?></td>
</tr>
<tr>
<td>BCC</td>
<td><?php echo $BCC ?></td>
</tr>
<tr>
<td>RBCC</td>
<td><?php echo $RBCC ?></td>
</tr>
<tr>
<td>BOB</td>
<td><?php echo $BOB ?></td>
</tr>
<tr>
<td>BP</td>
<td><?php echo $BP ?></td>
</tr>
<tr>
<td>BJ</td>
<td><?php echo $BJ ?></td>
</tr>
<tr>
<td>1ST</td>
<td><?php echo $first ?></td>
</tr>
<tr>
<td>2ND</td>
<td><?php echo $second ?></td>
</tr>
<tr>
<td>3RD</td>
<td><?php echo $third ?></td>
</tr>
<tr>
<td>RES</td>
<td><?php echo $RES ?></td>
</tr>
<tr>
<td>VHC</td>
<td><?php echo $VHC ?></td>
</tr>
</table>
You're doing well, just apply a filtering function to each row you recieve:
// SO UPDATE THE QUERY TO ONLY PULL THAT SHOW'S DOGS
$query = "SELECT * FROM result
WHERE first IS NOT NULL";
$result = mysqli_query($connection, $query);
if (!$result) {
trigger_error("Query Failed! SQL: $query - Error: ". mysqli_error($connection), E_USER_ERROR);
} else {
// Fetch results into array
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
// If results array is not empty
if ($data) {
echo '<table class="table" border="0"></div>
<tr>
<td>
<strong><?php echo $class_name ?></strong> - <h6>Entries: <?php echo $entries ?> Absentees: <?php echo $absentee ?></h6>
</td>
<td></td>
</tr>';
// Now let's walk through every record
array_walk($data, function($dogRecord) {
// Here we apply array_filter to each dog record, so that empty values (i.e. those evaluating to false) are filtered out
$dogRecord = array_filter($dogRecord);
// Now loop throw $dogRecord to build table
$collation = [
'DCC' => 'DCC',
'RDCC' => 'RDCC',
'BCC' => 'BCC',
'RBCC' => 'RBCC',
'BOB' => 'BOB',
'BP' => 'BOB',
'BJ' => 'BOB',
'1ST' => 'first',
'2ND' => 'second',
'3RD' => 'third',
'RES' => 'RES',
'VHC' => 'RES'
];
foreach ($dogRecord as $property => $value) {
echo '<tr>
<td>'.$collation[$property].'</td>
<td>'.$value.'</td>
</tr>';
}
});
echo '</table>';
}
}
Note that instead of simple foreach loop I'm using array_walk function. This is because since you extract variables for each record, you want undeclared (i.e. unoccupied) varables every time.
What about this:
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
// Show the table-row
}
}
The following code will iterate through each row in the result (while loop) and each key => value within each row (foreach loop); it will then check if a value is not null or the key is not equal to 'first' (if statement) and echo the results in the table element. I'm not sure I fully understood your question but I hope this helps in some small way.
<table>
<?php
if($result){
while($row = mysqli_fetch_assoc($result))
foreach($row as $key => $value){
if($value != null && $key != 'first'){
echo '<tr>';
echo '<td>' . $key . '</td>';
echo '<td>' . $value . '</td>';
echo '</tr>';
}
}
}
?>
</table>

getting value of array check box and textbox in table

i'm a beginner in php and i'm hoping that somebody here can help me in this.
i have a table that has a check box to select an item and a text box to indicate the quantity the person wants to borrow. i was wondering how i can retrieve both these data and then save them in my database.
here is a part of my code:
<td width="30">
<input id="optionsCheckbox" class="uniform_on" name="selector[]" type="checkbox" value="<?php echo $id; ?>">
</td>
<td><?php echo $row['item_code']; ?></td>
<td><?php echo $row['item_name']; ?></td>
<td align="center">
<img class="img-rounded" src="<?php echo $row['item_image'];?>" border="0" onMouseOver="showtrail('<?php echo $row['item_image'];?>','<?php echo $row['item_code'].": ".$row['item_name'];?> ',200,5)" onMouseOut="hidetrail()"></a></td>
<td><?php echo $row['item_quantity'] - $row['item_consumption']; ?> <?php echo $row['unit']; ?></td>
<td><input type="text" name="consume[]" pattern="[0-9]{1,4}"/></td>
here's what i have so far:
$id=$_POST['selector'];
$consume= $_POST['consume'];
$N = count($id);
for($i=0; $i < $N; $i++)
{
$query = $conn->query("select * from item where item_id ='$id[$i]'")or die(mysql_error());
$row = $query->fetch();
$code = $row['item_code'];
$name = $row['item_name'];
echo $code; echo $name;
echo $id;
}
$x = count($consume);
for($y=0; $y < $x; $y++)
{echo $consume;
}
the echos are just for checking if the data goes through. i'm just making sure they do before i make a query for table insertion.
what i'm trying to do is to post them on another page, display them in a table (a la shopping cart) and then make the borrower fill out a form with his details.
ok, using gul's answer below, this is what i did:
$id = $_POST['selector'];
$consume = $_POST['consume'];
//array var for getting the values
$ids = ''; $consumes='';
//loop the posted array
for($i=0;$i<count($id);$i++)
{
$ids .= $id[$i].',';
$consumes.="'".$consume[$i]."',";
}
//remove the last comma
$ids = substr($ids,0,-1);
$consumes = substr($consumes,0,-1);
$query = $conn->query("select * from item where item_id IN($ids)")or die(mysql_error());
//table element
echo "<table border='1' style='border-collapse:
collapse;border-color: silver;'>";
echo "<tr style='font-weight: bold;'>";
echo "<td width='150' align='center'>Item Code</td>";
echo "<td width='150' align='center'>Item Name</td>";
echo "<td width='150' align='center'>Quantity</td>";
echo "</tr>";
//get data in table
$row = $query->fetch();
$code = $row['item_code'];
$name = $row['item_name'];
$table ="";
$table.="<tr>";
$table.="<td>".$code."</td>";
$table.="<td>".$name."</td>";
$table.="<td>".$consumes."</td>";
$table.="</tr>";
$table.="</table>";
//echo the table
echo $table;
however, when i select multiple items, only the last one shows up, but the consumes show up like this:
consume shows in one cell with single quotes and comma. help?
Try like this:
//first get the post
$id = $_POST['selector'];
$consume = $_POST['consume'];
//array var for getting the values
$ids = ''; $consumes='';
//loop the posted array
for($i=0;$i<count($id);$i++)
{
$ids .= $id[$i].',';
//$consumes.="'".$consume[$i]."',";
}
//remove the last comma
$ids = substr($ids,0,-1);
$query = $conn->query("select * from item where item_id IN($ids))or die(mysql_error());
//table element
$table = "<table border='1'>";
$table.="<tr>";
$table.="<th>Code</th><th>Name</th>";
$table.="</tr>";
//get data in table
$row = $query->fetch();
$code = $row['item_code'];
$name = $row['item_name'];
$table.="<tr>";
$table.="<td>".$code."</td>";
$table.="<td>".$name."</td>";
$table.="</tr>";
$table.="</table>";
//echo the table
echo $table;
ok, so i tried this and it worked. thanks to gul for helping me.
$id = $_POST['selector'];
$consume = $_POST['consume'];
//array var for getting the values
$data = array();
//loop the posted array
for($i=0;$i<count($id);$i++)
{
$row = array('selector'=>$id[$i],'consume'=>$consume[$i]);
//push in array
array_push($data,$row);
$query = $conn->query("select * from item where item_id ='$id[$i]'")or die(mysql_error());
$row = $query->fetch();
$code = $row['item_code'];
$name = $row['item_name'];
while ($row = $query->fetch()) {
$id = $row['id'];
}
?>
<tr>
<td><?php echo $code; ?></td>
<td><?php echo $name; ?></td>
<td><?php echo $consume[$i]; ?></td>
<td></td>
</tr>
<?php } ?>
</tbody>
</table>

How to make 4 items in a row using while loop?

I'm trying to display my products from the database. I'm trying to split it using the if 4%=0, but I can't get it to display 4 items in a row.
Here is my codes:
<table>
<tr>
<?php
include "connect_to_mysql.php";
$split = 0;
$display_all = mysql_query("SELECT * FROM products
ORDER BY FIELD(category, 'ipad','iphone','others')");
while($row=mysql_fetch_array($display_all)) {
$id = $row['id'];
$product_code = $row['product_code'];
$title = $row['title'];
$price = $row['price'];
$split++;
if ($split%4==0){
echo '</tr><tr>';
}
?>
<td>
<table class="normal_text" align="center">
<tr>
<td><a href="product.php?product_id=<?php echo $id?>">
<img width="200px" height="133px" src="products/<?php echo $product_code?>.jpg" />
</a></td>
</tr>
<tr>
<td align="center" style="font-weight:bold"><?php echo $title;?></td>
</tr>
<tr>
<td align="center">$<?php echo $price;?></td>
</tr>
</table>
</td>
<?php
}
?>
</tr>
</table>
You've got the PHP logic before, rather than inside your HTML table output.
Try reorganizing like this:
<?php
include "connect_to_mysql.php";
$split = 0;
$display_all = mysql_query("SELECT * FROM products
ORDER BY FIELD(category, 'ipad','iphone','others')");
?>
<table class="normal_text" align="center">
<tr>
<?php
while($row=mysql_fetch_array($display_all)) {
$id = $row['id'];
$product_code = $row['product_code'];
$title = $row['title'];
$price = $row['price'];
// output product details -- note use of quotes to include PHP vars
$rowHTML = "<td><a href='product.php?product_id=$id'>";
$rowHTML .= "<img width='200px' height='133px' src='products/$product_code.jpg' />";
$rowHTML .= "</a><br/>";
$rowHTML .= "<strong>$title</strong>";
$rowHTML .= "$price</td>";
echo $rowHTML;
$split++;
if ($split%4==0){
echo '</tr><tr>';
}
}
?>
</tr>
</table>
while($row=mysql_fetch_assoc($display_all)) {
$id = $row['id'];
$product_code = $row['product_code'];
$title = $row['title'];
$price = $row['price'];
if ($split % 4 === 0) echo "\n<tr>";
?>
// ONLY <td> CODE </td> here. NO <tr> and NO </table>
<?php
if ($split % 4 === 3) echo "</tr>";
$split++;
}
?>
You are starting and ending at same time and then putting table for each.
You want to start <tr> when %4==0 and end </tr> when %4==3.
Rather than use modulus (%), just add a second variable called $cols, assign it to the amount of columns you want, and compare it. For example:
$rows = 1;
$cols = 4;
$display_all = mysql_query("SELECT * FROM products ORDER BY FIELD(category, 'ipad','iphone','others')");
while($row=mysql_fetch_array($display_all)) {
$id = $row['id'];
$product_code = $row['product_code'];
$title = $row['title'];
$price = $row['price'];
$split++;
if ($rows==$cols){
echo '</tr><tr>';
$rows = 1;
}

Displaying Reminders page from MySQL Database

I've created a PHP program for adding and viewing reminders. The add page works, but I'm having some trouble displaying them properly. How should I code this to only get the actual data? Also, how could I put this into an HTML table? (i.e. column for name, description, and date; rows are the retrieved data)
Thanks
When I open the file in my browser I get this as an output:
Array ( [reminderID] => 14 [reminderName] => Test [reminderDescript] => Test_Descript [reminderDate] => 2012 05 7 )
Code:
<?php include 'header.php'; ?>
<?php include 'database.php'; ?>
<div id="content">
<h1>Reminder List</h1>
<table align ="center">
<thead>
<tr>
<td>Name</td>
<td>Description</td>
<td>Date</td>
</tr>
</thead>
<?php
$query = 'SELECT * FROM reminder_event';
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)) {
print_r($row);
}
?>
</table>
<p><a href='reminder_add.php'>Add Reminder</a></p>
</div>
<?php include 'footer.php'; ?>
print_r() is a diagnostic tool for debugging, not to be used for real output. Instead, output HTML to a table using the array keys fetched from your row.
// Open a table
echo "<table>";
while($row = mysql_fetch_assoc($result)) {
// Output each row
echo "<tr>
<td>{$row['reminderName']}</td>
<td>{$row['reminderDescript']}</td>
<td>{$row['reminderDate']}</td>
</tr>";
}
// Close the table
echo "</table>";
Better still, escape each of the values for HTML output with [htmlspecialchars()] (http://us3.php.net/manual/en/function.htmlspecialchars.php) before output to prevent cross-site scripting attacks and broken HTML if characters like < > & are encountered in the values.
echo "<table>";
while($row = mysql_fetch_assoc($result)) {
// Encode all values for HTML output
$name = htmlspecialchars($row['reminderName']);
$desc = htmlspecialchars($row['reminderDescript']);
$date = htmlspecialchars($row['reminderDate']);
// Then output the encoded values
echo "<tr><td>$name</td><td>$desc</td><td>$date</td></tr>";
}
echo "</table>";
Change:
while($row = mysql_fetch_assoc($result)) {
print_r($row);
}
To:
while($row = mysql_fetch_assoc($result)) {
echo $row['reminderID'];
echo $row['reminderName'];
echo $row['reminderDescript'];
echo $row['reminderDate'];
}
You can echo those values out in whatever HTML you'd like. So, for example, if you want it in a table you would do something like this:
echo "<table><tr>";
while($row = mysql_fetch_assoc($result)) {
echo "<td>" . $row['reminderID'] . "</td>";
echo "<td>" . $row['reminderName'] . "</td>";
echo "<td>" . $row['reminderDescript'] . "</td>";
echo "<td>" . $row['reminderDate'] . "</td>";
}
echo "</tr></table>";
You can clean that up a bit to take some (or all) of the HTML out of the PHP.
<?php include 'header.php'; ?>
<?php include 'database.php'; ?>
<div id="content">
<h1>Reminder List</h1>
<table>
<thead><tr><td>id</td><td>name</td><td>description</td><td>date</td></tr></thead>
<tbody>
<?php
$query = 'SELECT * FROM reminder_event';
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)) { ?>
<tr>
<td><?php echo $row['reminderID']; ?></td>
<td><?php echo $row['reminderName']; ?></td>
<td><?php echo $row['reminderDescript']; ?></td>
<td><?php echo $row['reminderDate']; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
<p><a href='reminder_add.php'>Add Reminder</a></p>
</div>
<?php include 'footer.php'; ?>

Categories