I'm very new to PHP and MySQLI, however, I have been dabbling with them for a couple of years.
I am working on adding a search function for some photos I have on my website based off of 3 criteria.
I've been successful in implementing the script on a different page, which does not include the syntax for the page limits. However, now, when I add in my $where_stmt code, I end up with some errors, and I believe it has to do with the placement of a needed }.
The script in question is:
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
if (!defined('DB_SERVER')) define('DB_SERVER', 'xxx');
if (!defined('DB_USER')) define('DB_USER', 'xxx');
if (!defined('DB_PASSWORD')) define('DB_PASSWORD', 'xxx');
if (!defined('DB_TABLE')) define('DB_TABLE', 'xxx');
// The procedural way
$mysqli = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_TABLE);
$mysqli->set_charset("utf8");
$mysqli->query("SET NAMES 'utf8'");
if (mysqli_connect_errno($mysqli)) {
trigger_error('Database connection failed: ' . mysqli_connect_error(), E_USER_ERROR);
}
// This first query is just to get the total count of rows
$sql = "SELECT COUNT(*) FROM tbl_photos";
$query = mysqli_query($mysqli, $sql);
$row = mysqli_fetch_row($query);
// Here we have the total row count
$rows = $row[0];
// This is the number of results we want displayed per page
$page_rows = 16;
// This tells us the page number of our last page
$last = ceil($rows/$page_rows);
// This makes sure $last cannot be less than 1
if($last < 1){
$last = 1;
}
// Establish the $pagenum variable
$pagenum = 1;
// Get pagenum from URL vars if it is present, else it is = 1
if(isset($_GET['pn'])){
$pagenum = preg_replace('#[^0-9]#', '', $_GET['pn']);
}
// This makes sure the page number isn't below 1, or more than our $last page
if ($pagenum < 1) {
$pagenum = 1;
} else if ($pagenum > $last) {
$pagenum = $last;
}
// This sets the range of rows to query for the chosen $pagenum
$limit = 'LIMIT ' .($pagenum - 1) * $page_rows .',' .$page_rows;
if(isset($_POST['submit']))
if(isset($_GET['go']))
if(isset($_REQUEST['submited'])) {
$tid = $_POST['tID'];
$lvmid = $_POST['lvmID'];
$lid = $_POST['lID'];
$where_stmt="";
// query only for LuchtvaartmaatschappijID (LVMID)
if((isset($lvmid) && !empty($lvmid)) && (!isset($tid) || empty($tid)) && (!isset($lid) || empty($lid)))
{
$where_stmt="WHERE lvm.luchtvaartmaatschappijID='".$lvmid."'";
}
// query only for ToestelID
elseif((isset($tid) && !empty($tid)) && (!isset($lvmid) || empty($lvmid)) && (!isset($lid) || empty($lid)))
{
$where_stmt="WHERE t.toestelID = '".$tid."'";
}
// query only for luchthaven
elseif((isset($lid) && !empty($lid)) && (!isset($lvmid) || empty($lvmid)) && (!isset($tid) || empty($tid)))
{
$where_stmt="WHERE img_location = '".$lid."'";
}
// query only for Luchtvaartmaatschappij and Toestel
elseif((isset($lvmid) && !empty($lvmid)) && (isset($tid) || !empty($tid)) && (!isset($lid) || empty($lid)))
{
$where_stmt="WHERE lvm.luchtvaartmaatschappijID='".$lvmid."' and t.toestelID='".$tid."'";
}
// query only for Luchtvaartmaatschappij and luchthaven
elseif((isset($lvmid) && !empty($lvmid)) && (isset($lid) || !empty($lid)) && (!isset($tid) || empty($tid)))
{
$where_stmt="WHERE lvm.luchtvaartmaatschappijID='".$lvmid."' and img_location = '".$lid."'";
}
// query for luchtvaartmaatschappij, toestel and luchthaven
elseif((isset($lvmid) && !empty($lvmid)) && (isset($tid) && !empty($tid)) && (isset($lid) && !empty($lid)))
{
$where_stmt="WHERE lvm.luchtvaartmaatschappijID='".$lvmid."' and t.toestelID='".$tid."' and img_location = '".$lid."'";
}
else
{
//where statement should be excluded as no filters are available
}
// This is your query again, it is for grabbing just one page worth of rows by applying $limit
$sql = "
SELECT randimgID, img_location, img_lvm, img_file, img_nmr, img_t, t.toestel, l.luchthavennaam, lvm.luchtvaartmaatschappij, lvm.luchtvaartmaatschappijID, t.toestelID
FROM tbl_photos p
LEFT JOIN tbl_luchthaven l
ON p.img_location = l.luchthavenID
LEFT JOIN tbl_luchtvaartmaatschappij lvm
ON p.img_lvm = lvm.IATAcode
LEFT JOIN tbl_toestel t
ON p.img_t = t.toestelID
$where_stmt
ORDER BY lvm.luchtvaartmaatschappij, t.toestel ASC, p.img_nmr ASC $limit";
$query = mysqli_query($mysqli, $sql);
/* determine number of rows result set */
$row_cnt = mysqli_num_rows($query);
// This shows the user what page they are on, and the total number of pages
$textline1 = "beelden (<b>$rows</b>)";
$textline2 = "Page <b>$pagenum</b> of <b>$last</b>";
// Establish the $paginationCtrls variable
$paginationCtrls = '';
// If there is more than 1 page worth of results
if($last != 1){
/* First we check if we are on page one. If we are then we don't need a link to
the previous page or the first page so we do nothing. If we aren't then we
generate links to the first page, and to the previous page. */
if ($pagenum > 1) {
$previous = $pagenum - 1;
$paginationCtrls .= '<li class="page-item"><a class="page-link" href="'.$_SERVER['PHP_SELF'].'?pn='.$previous.'">vorige</a> </li>';
// Render clickable number links that should appear on the left of the target page number
for($i = $pagenum-4; $i < $pagenum; $i++){
if($i > 0){
$paginationCtrls .= '<li class="page-item"><a class="page-link" href="'.$_SERVER['PHP_SELF'].'?pn='.$i.'">'.$i.'</a> </li>';
}
}
}
// Render the target page number, but without it being a link
$paginationCtrls .= '<li class="page-item active">
<a class="page-link" href="#">'.$pagenum.' <span class="sr-only">(current)</span></a>
</li>';
// Render clickable number links that should appear on the right of the target page number
for($i = $pagenum+1; $i <= $last; $i++){
$paginationCtrls .= '<li class="page-item"><a class="page-link" href="'.$_SERVER['PHP_SELF'].'?pn='.$i.'">'.$i.'</a> </li> ';
if($i >= $pagenum+4){
break;
}
}
// This does the same as above, only checking if we are on the last page, and then generating the "Next"
if ($pagenum != $last) {
$next = $pagenum + 1;
$paginationCtrls .= '<li class="page-item"><a class="page-link" href="'.$_SERVER['PHP_SELF'].'?pn='.$next.'">volgende</a> </li>';
}
}
$list = '';
$items_in_row = 2 ;
$index = 0 ;
echo "<table width='100%' cellspacing='1' border='0'>
<tr>";
while($row = mysqli_fetch_assoc($query)) {
$img_location = $row['luchthavennaam'];
$img_lvm = $row['img_lvm'];
$l = htmlspecialchars($row['luchtvaartmaatschappij']);
$lvmID = $row['luchtvaartmaatschappijID'];
$img_nmr = $row['img_nmr'];
$t = $row['toestel'];
$tid = $row['toestelID'];
$f = $row['img_file'];
$rID = $row['randimgID'];
$img_file = $row['img_file'];
$image = "http://globe-trekking.com/vg/img/gallery/$img_lvm/$img_file";
$link = "http://globe-trekking.com/vg/gallery/details.php?pid=$rID&lvmID=$lvmID&in=$img_nmr";
$index++ ;
echo "<td width='370' align='left' valign='top' bgcolor='#292960'> ";
echo "<table width='540' border='0' cellpadding='0' cellspacing='0'>";
echo "<tbody>";
echo " <tr>";
echo " <td height='15' colspan='3' bgcolor='#292960'></td>";
echo " </tr>";
echo " <tr>";
echo " <td height='15' colspan='3' bgcolor='#000033'></td>";
echo " </tr>";
echo "<tr>";
echo " <td width='15' bgcolor='#000033'> </td>";
echo " <td bgcolor='#000033'><a href='" . $link ."'><img src='".$image."' width='510'></a></td>";
echo " <td width='15' bgcolor='#000033'></td>";
echo "</tr>";
echo "<tr>";
echo " <td bgcolor='#000033'> </td>";
echo " <td bgcolor='#000033'><table width='510' border='0' align='center' cellpadding='0' cellspacing='0'>";
echo " <tr>";
echo " <td height='15' colspan='2' valign='top' style='text-align: left'> </td>";
echo " </tr>";
echo " <tr>";
echo " <td width='72%' valign='top' style='text-align: left'><span style='font-size: 18px; color: #DEDEDE'><a class='airline' href='gallery_lvm.php?lvmid=$lvmID'>" . $l . "</a></span></td>";
echo " <td width='28%' style='text-align: left'><span style='font-size: 14.5px; color: #DEDEDE'>Reg: <a class='airline' href='gallery_reg.php?reg=$img_nmr'>" . $img_nmr . "</a></span></td>";
echo " </tr>";
echo " <tr>";
echo " <td height='10' colspan='2' valign='top' style='text-align: left'></td>";
echo " </tr>";
echo " <tr>";
echo " <td valign='top' style='text-align: left'><span style='font-size: 14.5px; color: #DEDEDE'><a class='airline' href='gallery_t.php?tid=$tid'>" . $t . "</a></span></td>";
echo " <td style='text-align: left'> </td>";
echo " </tr>";
echo " <tr>";
echo " <td height='10' colspan='2' valign='top' style='text-align: left'></td>";
echo " </tr>";
echo " <tr>";
echo " <td colspan='2' valign='top' style='text-align: left'><span style='font-size: 14.5px; color: #DEDEDE'>" . $img_location . "</span><br>
<br>
</td>";
echo " </tr>";
echo " <tr>";
echo " <td style='text-align: left'> </td>";
echo " <td style='text-align: left'> </td>";
echo " </tr>";
echo " </table></td>";
echo " <td bgcolor='#000033'> </td>";
echo "</tr>";
echo "<tr>";
echo " <td> </td>";
echo " <td> </td>";
echo " <td> </td>";
echo "</tr>";
echo " </tbody>";
echo " </table>";
echo " </td>";
if ($index%$items_in_row == 0){
echo " </tr>";
echo " <tr>";
}
}
echo " </tr>";
echo " </table>";
// Close your database connection
mysqli_close($mysqli);
?>
<br />
<nav aria-label="Page Navigation">
<ul class="pagination justify-content-center">
<div class="pagination"><?php echo $paginationCtrls; ?></div>
</ul>
</nav>
<br />
</div>
<br />
<br />
</div>
<?php include '../includes/menu/footer.php'; ?>
</body>
</html>
When I add it after the last else statement, I end up with an error that indicate
Notice: Undefined variable: where_stmt in /xxx/xxx/public_html/vg/gallery/search_post.php on line 174
// query for luchtvaartmaatschappij, toestel and luchthaven
elseif((isset($lvmid) && !empty($lvmid)) && (isset($tid) && !empty($tid)) && (isset($lid) && !empty($lid)))
{
$where_stmt="WHERE lvm.luchtvaartmaatschappijID='".$lvmid."' and t.toestelID='".$tid."' and img_location = '".$lid."'";
}
else
{
//where statement should be excluded as no filters are available
}
}
If I add it just before the mysqli_close() then it throws an error of:
PHP Notice: Undefined variable: paginationCtrls in
/xxx/xxx/public_html/vg/gallery/search_post.php on line 325
If I leave it out all together I get the following red x error in the web editor my hosting company provides me with:
Unexpected syntax, error $E0F
At this point, I'm not sure where this should be placed.
I should note that I can get the code to work when I get rid of the $where_stmt and the code above the $sql query.
I can recommend you to have a look at ORM libraries like http://propelorm.org/documentation/reference/model-criteria.html#finding-objects to avoid handwritten SQL and concatenated where clauses.
Also make sure that $paginationCtrls is declared before using it.
Related
I'm having a problem with PHP pagination.
When I click on the next page to see next results, pagination links and data just disappear.
I tried various Pagination classes, but decided to stop on this solution.
Will be extremely grateful if someone helps to find a fix.
<html>
<head>
<title></title>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<?Php
require "config_pag.php";
$field = $_POST['field'];
$state = $_POST['state'];
$page_name="search.php";
$start=$_GET['start'];
if(strlen($start) > 0 and !is_numeric($start)){
echo "Data Error";
exit;
}
$eu = ($start - 0);
$limit = 2;
$this1 = $eu + $limit;
$back = $eu - $limit;
$next = $eu + $limit;
$nume = $dbo->query("select count(id) from posts WHERE state = '$state' AND field = '$field'")->fetchColumn();
echo "<TABLE class='t1'>";
echo "<tr><th>ID</th><th>State</th><th>Fields</th><th>Description</th></tr>";
$query=" SELECT * FROM posts WHERE state = '$state' AND field = '$field' limit $eu, $limit ";
foreach ($dbo->query($query) as $row) {
$m=$i%2;
$i=$i+1;
echo "<tr class='r$m'><td>".$row['id']."</td><td>".$row['state']."</td><td>".$row['field']."</td><td>".$row['description']."</td></tr>";
}
echo "</table>";
if($nume > $limit ){
echo "<table align = 'center' width='50%'><tr><td align='left' width='30%'>";
if($back >=0) {
print "<a href='$page_name?start=$back'><font face='Verdana' size='2'>PREV</font></a>";
}
echo "</td><td align=center width='30%'>";
$i=0;
$l=1;
for($i=0;$i < $nume;$i=$i+$limit){
if($i <> $eu){
echo " <a href='$page_name?start=$i'><font face='Verdana' size='2'>$l</font></a> ";
}
else { echo "<font face='Verdana' size='4' color=red>$l</font>";}
$l=$l+1;
}
echo "</td><td align='right' width='30%'>";
if($this1 < $nume) {
print "<a href='$page_name?start=$next'><font face='Verdana' size='2'>NEXT</font></a>";}
echo "</td></tr></table>";
}
?>
</html>
For the past 2 days I've been looking for a pagination script of sorts, and I found this one which I'm starting to implement on my website.
The code is the following:
<?php
if (!(isset($pagenum)))
{
$pagenum = 1;
}
$data = mysqli_query($lig,"SELECT * FROM requisicao") or die("data");
$rows = mysqli_num_rows($data);
$page_rows = 5;
$last = ceil($rows/$page_rows);
if ($pagenum < 1)
{
$pagenum = 1;
}
elseif ($pagenum > $last)
{
$pagenum = $last;
}
$max = 'limit ' .($pagenum - 1) * $page_rows .',' .$page_rows;
$data_p = mysqli_query($lig,"SELECT * FROM requisicao $max") or die("data_p");
while($info = mysqli_fetch_assoc( $data_p ))
{
?>
<tr>
<td><?php print $info['id_requisicao']; ?> </td>
<td><?php print $info['username']; ?> </td>
<td><?php print $info['nome_servico']; ?> </td>
<td><?php print $info['data_requisicao']; ?> </td>
<td><?php print $info['estado_requisicao']; ?> </td>
<td><?php print $info['prioridade']; ?> </td>
<td><?php print $info['total']; ?> </td>
<td align="center">+</td>
<tr>
<?php
}
?>
</tbody>
</table>
<?php
if ($pagenum == 1)
{
}
else
{
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=1'> <<-Início</a> ";
echo " ";
$previous = $pagenum-1;
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$previous'> <-Anterior</a> ";
}
echo " ---- ";
if ($pagenum == $last)
{
}
else {
$next = $pagenum+1;
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$next'>Seguinte -></a> ";
echo " ";
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$last'>Última ->></a> ";
}
?>
I'm getting the first 5 rows out of it, but when I press Seguinte (which is Next) it changes the link (TO PAGE 2) but it doesn't change the values that get outputed. Basically, it always shows page 1.
I've also looked into several similar questions but I haven't found solutions that fix my problem.
Thanks in advance, and my apologies if this is a simple problem and I'm just overlooking things :s
The problem is that $pagenum will be initialized as 1, anyway.
Instead of:
if (!(isset($pagenum)))
{
$pagenum = 1;
}
Try writing this:
if (!isset($_REQUEST['pagenum']) || !is_int($_REQUEST['pagenum']))
{
$pagenum = 1;
} else {
$pagenum = (int)$_REQUEST['pagenum'];
}
You may find some more info handling HTTP Request variables here
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 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) ?>
Too many edits to keep track of, but I have simplified the issue. I have this code in my index.php:
<div class="calendar_top">
<?php
include(SITE_ROOT . "/includes/sub_top_divs.php"); ?>
</div>
<table class="tablebodycontainer"><tr><td>
<?php
include(SITE_ROOT . "/includes/view-monthly-calendar-ajax.php");
?>
</td></tr></table>
<?php include(SITE_ROOT . "/includes/copyright.php"); ?>
</div>
The subtop above contains the navigation links:
includes/subtop-divs.php:
<?php
//include(SITE_ROOT . "/includes/set-variables.php");//dateFormat($date)
echo "<table class='navtabs' cellpadding='0' cellspacing='0'>";
echo "<tr><td class='right'>";
echo buildMenuNavigation($currentPageIndex);
echo '</td></tr></table>';
?>
Here is that buildMenuNavigation function:
function buildMenuNavigation($currentIndex=0) {
$navtabs = array(
'0'=>array('Monthly'=>'index.php'),
'1'=>array('Daily'=>'agenda.php'),
'2'=>array('Admin'=>'admin/view-timelines.php'),
'3'=>array('Help'=>'help.php'),
);
$sep = '<li> | </li>';$builtNav=array();
foreach($navtabs as $index=>$tablinks) {
foreach($tablinks as $key=>$value) {
$class='';
if($index==$currentIndex) {
$class=' class="selected"';
}
//pr($value);
$builtNav[] = '<li><a href="' . SITE_URL . '/' . $value.'"' . $class .'> '.$key.' </a></li>';
}
}
return '<ul>' . implode($sep,$builtNav) . '</ul>';
}
The only data that actually changes when switching pages is the contents in the above:
<?php
include(SITE_ROOT . "/includes/view-monthly-calendar-ajax.php");
?>
So this seems like a perfect candidate for ajax.
Here is the contents of /includes/view-monthly-calendar-ajax.php:
<?php
$counter = 0;
?>
<table class="tabbody">
<tr>
<td class='head unselectable'>Sun</td>
<td class='head unselectable'>Mon</td>
<td class='head unselectable'>Tue</td>
<td class='head unselectable'>Wed</td>
<td class='head unselectable'>Thu</td>
<td class='head unselectable'>Fri</td>
<td class='head unselectable'>Sat</td>
</tr>
<tr>
<?php
//echo $year."-".$month."-";
$flag = 0;
$daysInrow = 0;
for($i = 1; $i < $numDays+1; $i++, $counter++)
{
$daysInrow++;
$zero = "";
if($i < 10)
{
$zero = "0";
}
$t_date = $year."-".$month."-".$zero.$i;
//$t_date = "$year-$month-$i";
$timeStamp = strtotime($t_date);
$eventID = 0;
$eventName = " ";
$bgColor = "";
$funcBG = "setbgcolorMonth($i);";
if($i == 1)
{
// Workout when the first day of the month is
$firstDay = date("w", $timeStamp);
for($j = 0; $j < $firstDay; $j++, $counter++)
echo "<td class='tddaybox'></td>";
}
if($counter % 7 == 0)
{
$daysInrow = 1;
echo "</tr><tr>";
}
if(date("w", $timeStamp) == 0)
if($i == date("d") && $month == date("m") && $year == date("Y"))
$class = "class='today'";
else
$class = "class='weekend'";
else
if($i == date("d") && $month == date("m") && $year == date("Y"))
$class = "class='today'";
else
$class = "class='normal'";
$numric_time = getNumericTime($_SESSION['userData']['timezone']);//Get the numeric timezone
$query = "SELECT * FROM events WHERE date(convert_tz(StartDate,'+00:00','". $numric_time."'))='".$t_date."' AND UserID='" . $_SESSION['userData']['UserID'] ."' ORDER BY PTLType ASC";
//br();
$result = mysql_query($query);
if(mysql_num_rows($result))//cursor:hand;cursor:pointer;width:112px;
{
$funcBG = "";
echo "<td valign='top' class='a_cursor_width tddaybox' id='day$i' onclick='setbgcolorMonth($i)'>";
echo "<div class='td_overlow'>";
echo '<table style="width:100%;border:0;">';
echo '<tr class="rowColor"><td '.$class.'><div class="div_left">'.$i.'</div><div class="div_left_80" onclick="'.$funcBG.' get_event_popup(window.event, this, \''.SITE_URL.'/event-popup.php\', \'eventID='.$eventID.'\', \'date='.$date.'\', \'day='.$i.'\', \'type=M\');return false"> </div></td></tr>';
while($row = mysql_fetch_assoc($result))
{
$eventID = $row['EventID'];
$parentEventID = $row['ParentEventID'];
$eventName = stripslashes($row['EventName']);
$PTLType = $row['PTLType'];
$textclass = "title4";
$onclick_call = 'get_event_popup(window.event, this, \''.SITE_URL.'/event-popup.php\', \'eventID='.$eventID.'\', \'date='.$date.'\', \'day='.$i.'\', \'type=M\')';
if($PTLType != 0) {
$onclick_call = 'get_event_popup(window.event, this, \''.SITE_URL.'/timeline-popup.php\', \'eventID='.$eventID.'\', \'parentEventID='.$parentEventID.'\', \'type=M\')';
$bgColor = "";
$textclass = "redtext";
if($PTLType == 3) {
$textclass = "bluetext";
$display = "none";
} else {
$display = "block";
}
$event_name_wrapped = '<div>'.$eventName.'</div>';
} else {
$textclass = "mainEvent";
$display = "block";
$event_name_wrapped = '<div>'.$eventName.'</div>';
}
echo '<tr><td onclick="'.$onclick_call.';return false;" class="'.$textclass.' a_cursor" title="'.$eventName.'" style="display:'.$display.';">'.$event_name_wrapped.'</td></tr>';
}
echo '<tr><td onclick="get_event_popup(window.event, this, \''.SITE_URL.'/event-popup.php\', \'eventID=0\', \'date='.$date.'\', \'day='.$i.'\', \'type=M\');return false;" class="a_cursor"> </td></tr>';
echo "</table>";
echo "</div>";
echo "</td>";
}
else
{
echo '<td id="day'.$i.'" height="80" valign="top" onclick="'.$funcBG.' get_event_popup(window.event, this, \''.SITE_URL.'/event-popup.php\', \'eventID='.$eventID.'\', \'date='.$date.'\', \'day='.$i.'\', \'type=M\');return false;" class="tddaybox a_cursor">';
echo '<table style="width:100%;">';
echo "<tr class='rowColor'><td $class>$i</td></tr>";
echo "<tr><td> </td></tr>";
echo "</table>";
echo "</td>";
}
}
for($l=0;$l<7-$daysInrow;$l++)
{
echo "<td class='tddaybox'> </td>";
}
?>
</tr>
</table>
<?php
/*
if(isset($divRed))
{
$divRed = implode(",",$divRed);
echo "<div id='divRed1' style='display:none'>$divRed</div>";
}
else
{
echo "<div id='divRed1' style='display:none'>0</div>";
}
if(isset($divBlue))
{
$divBlue= implode(",",$divBlue);
echo "<div id='divBlue1' style='display:none'>$divBlue</div>";
}
else
{
echo "<div id='divBlue1' style='display:none'>0</div>";
}
if(isset($divMainEvent))
{
$divMainEvent= implode(",",$divMainEvent);
echo "<div id='divMainEvent1' style='display:none'>$divMainEvent</div>";
}
else
{
echo "<div id='divMainEvent1' style='display:none'>0</div>";
}
*/
?>
<div id='gig1' style='display:none'>0</div>
<div id='todo1' style='display:none'>0</div>
<div id='completed1' style='display:none'>1</div>
<input type="hidden" id='lastselectedday' value='' />
So the output for all of the above is correct now, but when I try and do this:
<form>
<input type="button" value="Display Message" onclick="getData('/Dev2/includes/view-monthly-calendar-ajax.php', 'targetDiv')">
</form>
<table class="tablebodycontainer">
<tr>
<td id="MainCalendarContainer">
<div class="ajaxswap" id="targetDiv">
</div>
The output of the ajax call doesn't execute the php.
First off, you shouldn't pull <script> elements via Ajax, they are not going to be interpreted and if they are, they are going to break everything on the second request.
Do some debugging by calling /Dev2/includes/view-monthly-calendar-ajax.php in your browser first. Check out the source code of what you are getting. PHP runs before the document is delivered, so there is no way to pull the HTML, but not the contents generated by PHP. They are one entity.
You either have an error in your PHP code that leads to the wrong output, or your PHP code is not being interpreted at all, which is easy to spot because the original PHP source code will be in the document's source code (which must never, ever happen).
The PHP code is processed by the server; the browser will never see it unless the web server glitches.
PHP is preprocessed before the data is sent to the client. The server parses and executes the php code and only sends what is output by the code. If you want to get the full file you would need to have it not processed by php, for instance by renaming the file extension to something else.
You should implement another php page such as...
getData('getPHP.php?page=/Dev2/includes/view-monthly-calendar-ajax.php', 'targetdic');
Then in that page you need to implement a method to load the php file as a string and return it. at the moment the php is being interpreted as you would expect.