I have 5 pictures stored in a folder and their links stored on the database.
I want to put them in a table of three columns on each row.
<body>
<center>
<table border='1'>
<?php
$host="";
$username="";
$password="";
$db_name="fruits_db";
$tbl_name="fruits_tbl";
$connection=mysqli_connect("$host","$username","$password","$db_name");
if (mysqli_connect_errno())
{
echo "The application has failed to connect to the mysql database server: " .mysqli_connect_error();
}
$result = mysqli_query($connection, "SELECT * FROM fruits_tbl")or die("Error: " . mysqli_error($connection));
$num_rows=mysqli_num_rows($result);
$rows = $num_rows/3;
for($i=1; $i<=$rows ; $i++)
{
echo "<tr>";
for($j=1; $j<=3; $j++)
{
while($row = mysqli_fetch_array($result))
{
echo
("<td width='180px' height='200px'>"
."<div class = 'fruit_image'>"
."<img src='"
.$row['fruit_image']
."'/>"
."</div>"
."<div class = 'fruit_title'>"
.$row['fruit_name']
."</div>"
."</td>"
);
}
}
echo "</tr>";
}
mysqli_close($connection);
?>
</table>
</center>
</body>
</html>
The above code I created, contains two FOR loops. The script should count the number of rows in the table, and then divide by 3(the number of columns on each row in the HTML table).
I wonder where I'm going wrong wit this code.
With your while($row = mysqli_fetch_array($result)){} inside your 1st for loop it will run through all your rows, before the outside loop runs 2nd/3rd time.
Here is another way to do it -
$counter = 1;
// start 1st row
echo "<tr>";
while($row = mysqli_fetch_array($result)){
// if the 4th cell, end last row, and start new row
if ($counter%3==1){
echo "</tr><tr>";
}
echo
"<td width='180px' height='200px'>"
."<div class = 'fruit_image'>"
."<img src='"
.$row['fruit_image']
."'/>"
."</div>"
."<div class = 'fruit_title'>"
.$row['fruit_name']
."</div>"
."</td>";
// increase the counter
$counter++;
}
// close the last row
echo "</tr>";
You're looping through all the results in the first table cell.
Try something like this instead:
for($i=1; $i<=$rows ; $i++) {
echo "<tr>";
for($j=1; $j<=3; $j++) {
$row = mysqli_fetch_array($result);
if ($row) {
echo(
"<td width='180px' height='200px'>"
."<div class = 'fruit_image'>"
."<img src='"
.$row['fruit_image']
."'/>"
."</div>"
."<div class = 'fruit_title'>"
.$row['fruit_name']
."</div>"
."</td>"
);
}
}
echo "</tr>";
}
If you just want to format the display with a new row after every 3 records, you could use the modulus operator:
$cntr = 0;
echo '<tr>';
while($row = mysqli_fetch_array($result)) {
$cntr++;
echo '
<td width="180px" height="200px">
<div class="fruit_image">
<img src="'.$row['fruit_image'].'" />
</div>
<div class="fruit_title">'.$row['fruit_name'].'</div>
</td>';
if ($cntr % 3 == 0 && $cntr != $num_rows)
echo '</tr><tr>';
}
echo '</tr>';
Keep in mind however that all the solutions presented so far may leave you with a last row with one or two td elements. You can fill this if you desire with empty <td> </td> columns.
print "<center><table border=1>
<tr>
<td>id</td>
<td>name</td>
<td>company</td>
<td>branch</td>
<td>job title</td>
<td>contact</td>
<td>email</td>
<td>mgs</td>
</tr>";
while($row=mysql_fetch_array($query))
{
print "<tr>";
for ($i=0;$i<=(count($row)/2);$i++)
{
print "<td>$row[$i]</td>";
} print"</tr>";
}
}
else{echo " <p>No Records Found</p>";}
<?php
function studentTable($name,$grade){
echo "<tr> <td>$name</td><td>$grade</td></tr>";
}
?>
<table style="width:100%" border="solid">
<tr>
<th>Name</th>
<th>Grade</th>
</tr>
<?php studentTable("Sarah", 90) ?>
Related
I need to get rid of the extra columns that appear on the right, outside the table headers.
how can I do that?
output of code below (image)
<?php
$players=4;
$round=$players;
$c=1;
$draw=true;
echo "<table>";
echo"<tr>
<th>Round 1</th>
<th>Round 2</th>
<th>Winner</th>
</tr>";
for ($row=1; $row <= $players; $row++) {
echo "<tr> \n";
while ($round >= 1) {
$p = $c;
$span=$players/$round;
if ($draw=true){
echo "<td rowspan=\"$span\">$c</td> \n";
}
$round=$round/2;
$c=$c+1;
}
$round=$players;
echo "</tr>";
}
echo "</table>";
?>
I have a table 'tblexam' which contains State,city,candidate.I want to fetch the data from this table using where clause.I am able to fetch the data but i want to add the sum of Candidate at the last row(As Shown In Picture) how can i do that .
$sql="SELECT *
FROM tblexam
WHERE state='UP'";
$cnt=1;
if($query->rowCount() > 0)
{
foreach($results as $result) {
$cnt=$cnt+1; ?>
<tr class="odd gradeX">
<td class="center"><?php echo htmlentities($cnt);?></td>
<td class="left"align="left"><?php echo htmlentities($result->state);?></td>
<td class="center" align="left"><?php echo htmlentities($result->city);?></td>
<td class="center"align="left"><?php echo htmlentities($result->candidate);?></td>
<?php } ?>
<td class="center"align="left"><?php echo htmlentities($result->Total);?></td>
</tbody>
</table>
Add total while iterating through rows and display it outside the loop, Sample code is given below
$sql = "SELECT * FROM tblexam WHERE city='UP'";
$result = $conn->query($sql);
$numRows = $result->num_rows;
if ($numRows> 0) {
$total = 0;
echo '<table border="1" cellpadding="5" cellspacing="0">';
echo '<tr>';
echo '<th>state</th>';
echo '<th>city</th>';
echo '<th>candidate</th>';
echo '</tr>';
while($row = $result->fetch_assoc()) {
$total+=$row['candidate'];
echo '<tr>';
echo '<td>'.$row['city'].'</td>';
echo '<td>'.$row['state'].'</td>';
echo '<td>'.$row['candidate'].'</td>';
echo '</tr>';
}
echo '<tr>';
echo '<td>Total</td>';
echo '<td> </td>';
echo '<td>'.$total.'</td>';
echo '</tr>';
echo '<table>';
}
Before you start looping the data you can create a variable which you set to 0, inside the loop you can add the result's total to this variable, after the loop, the variable will contain the grand total:
$total = 0;
foreach($results as $result) {
$total += (int)$result->Total;
...
}
// $total = 1425
we have an assignment for today in which we have to echo some data of the database. The data is month, case, vehicle_id. In a month there can be many cases and in a case there can be many vehicle_ids. What i have achieve to do is to show it in the following way
month st_case veh_id
1 10001 1000011
1 10002 1000021
1 10002 1000022
2 10058 1000581
using this code:
<table border="1">
<tr>
<th>month</th>
<th>st_case</th>
<th>veh_id</th>
</tr>
<?php
// Loop on rows in the result set.
for($ri = 0; $ri < $numrows; $ri++) {
echo "<tr>\n";
$row = pg_fetch_array($result, $ri);
echo " <td>", $row["month"], "</td>
<td>", $row["st_case"], "</td>
<td>", $row["veh_id"], "</td>
</tr>
";
}
pg_close($link);
?>
</table>
The problem is that what i really want to do is to make it show for each month the cases and for each case the vehicles.
1
10001
1000011
10002
1000021
1000022
2
10058
1000581
I tried to do something like this but it doesn't show correctly. If someone could help me with this i would be really thankfull.
<table border="1">
<tr>
<th>month</th>
<th>st_case</th>
<th>veh_id</th>
</tr>
<?php
// Loop on rows in the result set.
$currentmonth = 0;
for($ri = 0; $ri < $numrows; $ri++)
{
$row = pg_fetch_array($result, $ri);
if ($currentmonth != $row["month"])
{
echo "<tr>";
echo "<td>";
echo "<strong>".$row["month"]."</strong>";
echo "</td>";
echo "</tr>";
}
echo "<tr>";
echo "<td>".$row["st_case"]."</td>";
echo "</tr>";
echo "<tr>";
echo "<td>".$row["veh_id"]."</td>";
echo "</tr>";
$currentmonth = $row["month"];
}
pg_close($link);
?>
</table>
picture: http://i61.tinypic.com/2nb8vgl.png
$ret = pg_fetch_all($result);
$group = array();
foreach($ret as $v){
$group[$v['month']][$v['st_case']][] = $v['veh_id'];
}
foreach($group as $month=>$value){
echo $month."<br/>";
foreach($value as $st_case=>$v){
echo $st_case."<br/>";
foreach($v as $veh_id){
echo $veh_id."<br/>";
}
}
}
PS.then add some css to style your table
If you do not intend to display items in a table, do not use table
What you want is something like this:
<div class="result">
<div class="month_group">
<span class="month bold">1</span>
<div class="case_group">
<span class="case">10001</span>
<div class="veh_group">
<span class="veh_id">1000011</span>
</div>
<span class="case">10002</span>
<div class="veh_group">
<span class="veh_id">1000021</span>
<span class="veh_id">1000022</span>
</div>
</div>
</div>
<div class="month_group">
<span class="month">2</span>
<div class="case_group">
<span class="case">10058</span>
<div class="veh_group">
<span class="veh_id">1000081</span>
</div>
</div>
</div>
</div>
Then all that's left to do is applying simple css to give the classes some padding/margin.
HTML is a markup language. You structure the web page using the HTML tags. However, how it would look like depends more on css (which is why it's called Cascading Style Sheets).
Here's the rendering code. I have not tested it yet, and I have not touched PHP for sometime, but it should give you some general ideas:
echo "<div class=\"result\">";
for($ri = 0; $ri < $numrows; $ri++) {
$row = pg_fetch_array($result, $ri);
$month = $row["month"];
echo "<div class=\"month_group\">\n";
echo "<span class=\"month\">".$month."</span>\n";
echo "<div class=\"case_group\">\n";
for ($ci = $ri; $ci < $numrow; $ci++) {
if ($ci == $ri) {
$c_row = $row;
} else {
$c_row = pg_fetch_array($result, $ci);
}
if ($c_row["month"] != $month) {
// We have moved to another month
break;
}
$case = $c_row["st_case"];
echo "<span class=\"case\">".$case."</span>\n";
echo "<div class=\"veh_group\">\n";
for ($vi = $ci; $vi < $numrow; $vi++) {
if ($vi == $ci) {
$v_row = $c_row;
} else {
$v_row = pg_fetch_array($result, $vi);
}
if ($v_row["st_case"] != $case) {
// We have moved to another case
break;
}
$veh = $v_row["veh_id"];
echo "<span class=\"veh_id\">".$veh."</span>\n";
// we have already processed rows whose indexes are less or equal $vi
$ri = $vi;
}
echo "</div>";
}
echo "</div></div>";
}
Try this updated code
<table border="1">
<tr>
<th>month</th>
<th>st_case</th>
<th>veh_id</th>
</tr>
<?php
// Loop on rows in the result set.
$currentmonth = 0;
for($ri = 0; $ri < $numrows; $ri++)
{
$row = pg_fetch_array($result, $ri);
// Open the row
echo "<tr>";
echo "<td><strong>" . $row["month"] . "</strong></td>"; //open and close each column
echo "<td>".$row["st_case"]."</td>";
echo "<td>".$row["veh_id"]."</td>";
echo "</tr>"; //close the row
$currentmonth = $row["month"];
}
pg_close($link);
?>
</table>
You will also need to call the ORDER BY keyword in your MySQL statement to order by month.
Here is a simple tutorial on how to do this.
Here is a Demo of how it might look in your application.
Let me know if this helps and if i can be of any other help.
I am not very familiar with PHP or MySQL, but after researching here I have been able to learn and get very close to what I need and build my first sum query. I am trying to read the database and sum values based on several variables.
I need the reservation_pax from the reservations table where reservation_time is 8:00 where reservation_hidden = 0 and reservation_date is something. I can manually enter the date and it works. I am now trying to use a session code already in the script or find a way to to dynamically add based on selected date.
Here is the code I have working without the dynamic aspect or session.
$result = mysql_query("SELECT SUM(reservation_pax)
FROM reservations
WHERE reservation_time = '8:00:00'
AND reservation_date = '2014-10-27'
AND reservation_hidden ='0'") ;
if ($result === false) {
die(mysql_error()); // TODO: better error handling
}
while($row = mysql_fetch_array($result)) {
echo $row['SUM(reservation_pax)'];
}
Here is the full code of the page where I entered the above addition. Can anyone help me figure out how to call the selected date rather than having to manually enter.
<!-- Begin reservation table data -->
<br/>
<table class="global resv-table-small" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<?php
echo "<td class='noprint'> </td>";
echo "<td>Time</td>";
echo "<td>Guests/Type</td>";
echo "<td>Name</td>";
echo "<td>Special Instructions/Notes</td>";
echo "<td class='noprint'>Table</td>";
echo "<td class='noprint'>Status</td>";
echo "<td class='noprint'>Created</td>";
echo "<td class='noprint'>Details/Delete</td>";
echo "</tr>";
// Clear reservation variable
$reservations ='';
if ($_SESSION['page'] == 1) {
$reservations = querySQL('all_reservations');
}else{
$reservations = querySQL('reservations');
}
// reset total counters
$tablesum = 0;
$guestsum = 0;
if ($reservations) {
//start printing out reservation grid
foreach($reservations as $row) {
// reservation ID
$id = $row->reservation_id;
$_SESSION['reservation_guest_name'] = $row->reservation_guest_name;
// check if reservation is tautologous
$tautologous = querySQL('tautologous');
echo "<tr id='res-".$id."'>";
echo "<td";
// daylight coloring
if ($row->reservation_time > $daylight_evening){
echo " class='evening noprint'";
}else if ($row->reservation_time > $daylight_noon){
echo " class='afternoon noprint'";
}else if ($row->reservation_time < $daylight_noon){
echo " class='morning noprint'";
}
echo " style='width:10px !important; padding:0px;'> </td>";
echo "<td id='tb_time'";
// reservation after maitre message
if ($row->reservation_timestamp > $maitre['maitre_timestamp'] && $maitre['maitre_comment_day']!='') {
echo " class='tautologous' title='"._sentence_13."' ";
}
echo ">";
echo "<strong>".formatTime($row->reservation_time,$general['timeformat'])."</strong></td>";
echo "<td id='tb_pax'><strong class='big'>".$row->reservation_pax."</strong> <span class='noprint'>";
printType($row->reservation_hotelguest_yn);
//echo "<img src='images/icons/user-silhouette.png' class='middle'/>";
echo "</span></td><td style='width:10%' id='tb_name'><span class='noprint'>".printTitle($row->reservation_title)."</span><strong> <a id='detlbuttontrigger' href='ajax/guest_detail.php?id=".$id."'";
// color guest name if tautologous
if($tautologous>1){echo" class='tautologous tipsy' title='"._tautologous_booking."'";}
echo ">".$row->reservation_guest_name."</a></strong>";
// old reservations symbol
if( (strtotime($row->reservation_timestamp) + $general['old_days']*86400) <= time() ){
echo "<img src='images/icons/clock-bolt.png' class='help tipsyold middle smicon' title='"._sentence_11."' />";
}
// recurring symbol
if ($row->repeat_id !=0) {
echo " <img src='images/icons/loop-alt.png' alt='"._recurring.
"' title='"._recurring."' class='tipsy' border='0' >";
}
echo"</td><td style='width:10%' id='tb_note'>";
if ($_SESSION['page'] == 1) {
echo $row->outlet_name;
}else{
echo $row->reservation_notes;
}
echo "</td>";
if($_SESSION['wait'] == 0){
echo "<td class='big tb_nr' style='width:85px;' id='tb_table'><img src='images/icons/table_II.png' class='tipsy leftside noprint' title='"._table."' /><div id='reservation_table-".$id."' class='inlineedit'>".$row->reservation_table."</div></td>";
}
echo "<td class='noprint'><div>";
getStatusList($id, $row->reservation_status);
echo "</div></td>";
echo "<td class='noprint'>";
echo "<small>".$row->reservation_booker_name." | ".humanize($row->reservation_timestamp)."</small>";
echo "</td>";
echo "<td class='noprint'>";
// MOVE BUTTON
// echo "<a href=''><img src='images/icons/arrow.png' alt='move' class='help' title='"._move_reservation_to."'/></a>";
// WAITLIST ALLOW BUTTON
if($_SESSION['wait'] == 1){
$leftspace = leftSpace(substr($row->reservation_time,0,5), $availability);
if($leftspace >= $row->reservation_pax && $_SESSION['outlet_max_tables']-$tbl_availability[substr($row->reservation_time,0,5)] >= 1){
echo" <a href='#' name='".$id."' class='alwbtn'><img src='images/icons/check-alt.png' name='".$id."' alt='"._allow."' class='help' title='"._allow."'/></a> ";
}
}
// EDIT/DETAIL BUTTON
echo "<a href='?p=102&resID=".$id."'><img src='images/icons/pen-fill.png' alt='"._detail."' class='help' title='"._detail."'/></a> ";
// DELETE BUTTON
if ( current_user_can( 'Reservation-Delete' ) && $q!=3 ){
echo"<a href='#modalsecurity' name='".$row->repeat_id."' id='".$id."' class='delbtn'>
<img src='images/icons/delete.png' alt='"._cancelled."' class='help' title='"._delete."'/></a>";
}
echo"</td></tr>";
$tablesum ++;
$guestsum += $row->reservation_pax;
}
}
?>
</tbody>
<tfoot>
<tr style="border:1px #000;">
<td class=" noprint"></td><td></td>
<td colspan="2" class="bold"><?php echo $guestsum;?> <?php echo _guest_summary;?></td>
<td></td>
<td colspan="2" class="bold"><?php echo $tablesum;?> <?php echo _tables_summary;?></td>
<td colspan="2" class="bold"><?php
$result = mysql_query("SELECT SUM(`reservation_pax`) FROM `reservations` WHERE `reservation_time` = '8:00:00' AND `reservation_date` = '{$_SESSION['selectedDate']}' AND `reservation_hidden` ='0'") ;
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
while($row = mysql_fetch_array($result))
{
echo $row['SUM(reservation_pax)'];
}
?>
<?php echo '/ 40 ', _guest_summary, ' -8:00 AM';?></td>
<td></td>
<?php
if($_SESSION['wait'] == 0){
//echo "<td></td>";
}
?>
</tr>
</tfoot>
</table>
<!-- End reservation table data -->
you can use alias field, as:
$result = mysql_query("SELECT SUM(reservation_pax) AS reserve_sum
FROM reservations WHERE reservation_time = '8:00:00'
AND reservation_date = '2014-10-27'
AND reservation_hidden ='0'"
) ;
....
and get access it as:
while($row = mysql_fetch_array($result))
{
echo $row['reserve_sum'];
}
$result = mysql_query("SELECT SUM(reservation_pax) FROM reservations WHERE reservation_time = '8:00:00' AND reservation_date = '{$_SESSION['selectedDate']}' AND reservation_hidden ='0'") ;
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
while($row = mysql_fetch_array($result))
{
echo $row['SUM(reservation_pax)'];
}
?>
I'm not really familiar with Ajax Response - I have edited the PHP Ajax Search code from W3schools.com as follows :
<?php
require_once('connect_db.php');
$query = "select item_no from items";
$result = mysql_query($query);
$a = array();
while ($row = mysql_fetch_assoc($result)){
$a[] = $row['item_no'];
}
//get the q parameter from URL
$q=$_GET["q"];
//lookup all hints from array if length of q>0
if (strlen($q) > 0)
{
$hint="";
for($i=0; $i<count($a); $i++)
{
if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
{
if ($hint=="")
{
$hint=$a[$i];
}
else
{
$hint=$hint." , ".$a[$i];
}
}
}
}
// Set output to "no suggestion" if no hint were found
// or to the correct values
if ($hint == "")
{
$response="No Suggestion";
}
else
{
$response=$hint;
}
//output the response
echo "<table border=1><tr><td>".$response."</td></tr></table>";
?>
The output of the above code works perfectly, but they are all listed like this (2L500BU , 2L500GO , 2L500NA , 2L500RD , 2L802CA , 2L802WH , 2L803GR , 2L804BE , 2L804BK , 2L804CO , 2L805BU , 2L806BE , 2L806GR ) - Those numbers are Item No in mysql table called items.
Now :
1) I want to output the response into table with <tr> for each like this
2l500BU
2L500GO
.
.
.
.
etc.
2) Do you think its possible to output all table records from Mysql based on the hint entered as follows :
$sql="SELECT * FROM items WHERE item_no = '".**$hint**."'";
$result = mysql_query($sql);
echo "<table align='center' cellpadding='3' cellspacing='3' width='800px' border='1' font style='font-family:arial;'>";
echo "
<tr align=center>
<th style=font-size:18px; bgcolor=#20c500>Item Number</th>
<th style=font-size:18px; bgcolor=#20c500>QTY</th>
<th style=font-size:18px; bgcolor=#20c500>Actual Price</th>
<th style=font-size:18px; bgcolor=#20c500>Selling Price</th>
<th style=font-size:18px; bgcolor=#20c500>Difference</th>
<th style=font-size:18px; bgcolor=#20c500>Date</th>
</tr>";
while($row = mysql_fetch_assoc($result)){
echo "<tr align=center bgcolor=#e3e3e3>";
echo "<td style='font-size:18px; font-weight:bold;'>" . strtoupper($row['item_no']) . "</td>";
echo "<td style='font-size:18px; font-weight:bold;'>" . $row['qty'] . "</td>";
echo "<td style='font-size:18px; font-weight:bold;'>" . $row['actual_price'] . " <font style=font-size:12px;>JD</font></td>";
echo "<td style='font-size:18px; font-weight:bold;'>" . $row['discount_price'] . " <font style=font-size:12px;>JD</font></td>";
echo "<td style='font-size:18px; font-weight:bold;'>" . $row['difference_price'] . " <font style=font-size:12px;>JD</font></td>";
echo "<td style='font-size:18px; font-weight:bold;'>" . date("d-m-Y",strtotime($row['date'])) . "</td>";
echo "</tr>";
}
echo "<table>";
If you're wanting to fetch items from a database and display a row for each of them, this is how you'd do it with jQuery.
Your PHP script:
<?php
$mysqli = new mysqli('localhost', 'user', 'password', 'database');
$sql = "SELECT item_no FROM items";
$res = $mysqli->query($sql);
while ($row = $res->fetch_assoc()) {
$rows[] = $row['item_no'];
}
header('Content-Type: application/json');
echo json_encode($rows);
?>
And your HTML with the table:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<table>
<thead>
<tr>
<th scope="col">Item No.</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>
<script src="js/lib/jquery.js"></script>
<script>
$(document).ready(function() {
$.getJSON('yourscript.php', function(items) {
$.each(items, function(i, item) {
$('tbody').append('<tr><td>' + item + '</td></tr>);
});
});
});
</script>
I've also used MySQLi (MySQL improved) rather than the standard mysql_ functions, as the mysql_ library is deprecated and you should be using either MySQLi or PDO now.