Fixing a pagination error - php

I am having a problem with pagination within the tabs. In the second tab (candidate), when I press pagination 2 to navigate to the second page of the candidate table, I am returned to the first page of the contact table. If I go to the candidate tab after that I am on the right page. Where have I gone wrong?
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"> </script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/themes/start/jquery-ui.css"/>
<link type ="text/css" rel ="stylesheet" href = "testData.cs"/>
<script>
$(function(){
$('#tabs1,#tabs2').tabs();
});
</script>
<head>
<title>Candidate DB</title>
</head>
<body>
<div id ="tabs1" class ="contactForm">
<ul>
<li>List of Contacts</li>
<li>List of Candidates</li>
<li>Advanced Search</li>
</ul>
<div id ="tab1" class="contact" >
<table border="1" id="contact_info">
<tr>
<th>Contact Name</th>
<th>County</th>
</tr>
<?php
$DB_NAME = "Candidate";
$DB_USER ="root";
$DB_PASSWORD ="";
$DB_HOST ="localhost";
$con=mysql_connect("$DB_HOST", "$DB_USER", "$DB_PASSWORD") or die("Could not connect to MySQL");
mysql_select_db("$DB_NAME") or die ("No Database");
echo "Connected to Candidate Database </br></hr>" ;
$per_page=5;
$pages_query= mysql_query("SELECT COUNT(contact_id) FROM contact");
$pages = ceil(mysql_result($pages_query,0)/$per_page);
$page=(isset($_GET['page'])) ? (int)$_GET['page'] : 1;
$start=($page-1) * $per_page;
$sql=mysql_query("SELECT first_name, last_name, county from contact ORDER BY last_name ASC LIMIT $start, $per_page" );
$Fname = 'first_name';
$Lname = 'last_name';
$county = 'county';
while ( $row = mysql_fetch_object($sql)) {
echo "<tr>";
echo "<td>" . $row ->first_name . " " . $row->last_name. "</td>";
echo "<td>" . $row->county . "</td>";
echo "</tr>";
}
// close the loop
if ($pages>=1 && $page<= $pages ) {
for ($x=1; $x<=$pages; $x++)
{
echo ($x ==$page)? '<strong><a style="color:green" href="? page='.$x.'">'.$x. '</a></strong>_':''.$x. '_';
}
}
?>
</table>
</div>
<div id ="tab2" class="candidate" >
<table border="1" id="candidate_info">
<tr>
<th>Candidate Name</th>
<th>County</th>
</tr>
<?php
$per_pageR=5;
$pages_queryR= mysql_query("SELECT COUNT(candidate_id) FROM p_candidate");
$pagesR = ceil(mysql_result($pages_queryR,0)/$per_pageR);
$pageR=(isset($_GET['pageR'])) ? (int)$_GET['pageR'] : 1;
$startR=($pageR-1) * $per_pageR;
$sql2=mysql_query("SELECT R_first_name, R_last_name, R_county from p_candidate ORDER BY R_last_name ASC LIMIT $startR, $per_pageR" );
$R_name = 'R_first_name';
$R_name = 'R_last_name';
$R_county = 'R_county';
while ( $rowR = mysql_fetch_object($sql2)) {
echo "<tr>";
echo "<td>" . $rowR ->R_first_name . " " . $rowR->R_last_name. "</td>";
echo "<td>" . $rowR->R_county . "</td>";
echo "</tr>";
}
// close the loop
if ($pagesR>=1 && $pageR<= $pagesR ) {
for ($y=1; $y<=$pagesR; $y++)
{
echo ($y ==$pageR)? '<strong><a style="color:green" href="? pageR='.$y.'">'.$y. '</a></strong>_':''.$y. '_';
}
}
?>
</table>
</div>
</div>
</body>

If I understand correctly, try using the active option - http://api.jqueryui.com/tabs/#option-active - when you do .tabs() to make the candidate tab the active tab.
<script>
$(function(){
$('#tabs1,#tabs2').tabs(<?php if(isset($_GET['pageR'])) echo "{ active: 1 }"; ?>);
});
</script>
or
<script>
$(function(){
$('#tabs1,#tabs2').tabs(<?php if(isset($_GET['pageR'])) echo '"option", "active", -1'; ?>);
});
</script>
edit
You could bind the .tabs() first, and then set the active option. This should hopefully fix your formatting issue.
<script>
$(function(){
$('#tabs1,#tabs2').tabs();
<?php if(isset($_GET['pageR'])) { ?>
$('#tabs1').tabs("option", "active", -1)
<?php } ?>
});
</script>

Related

Query String PHP

I'm trying to get the Owner's details by clicking on their name from the table at the bottom.
<html>
<head>
<title>Home</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
window.onload = function()
{
timedHide(document.getElementById('co'), 10);
}
function timedHide(element, seconds)
{
if (element) {
setTimeout(function() {
element.style.display = 'none';
}, seconds*1000);
}
}
</script>
<?php
require 'Navbar.php';
?>
<h1>Welcome to Poppleton Dog Show! This year 50 owners entered 300 dogs in 10 events!</h1>
<?php
include './connection.php';
$sql = "SELECT owners.id AS id, owners.name AS Owner, owners.email AS Email, dogs.name AS Name, ROUND(avg(score), 1) AS avg_score, breeds.name AS breed_name, COUNT(entries.id) AS entries_count\n"
. "FROM entries\n"
. "JOIN dogs ON dogs.id = entries.dog_id\n"
. "JOIN breeds ON dogs.breed_id = breeds.id\n"
. "JOIN owners ON owners.id = dogs.owner_id\n"
. "GROUP BY dogs.id\n"
. "HAVING entries_count > 1\n"
. "ORDER BY `avg_score` DESC\n"
. "LIMIT 10";
$result = $conn->query($sql);
echo "<table '<td align='center'>
<tr>
<th>Owner</th>
<th>Email</th>
<th>Dog</th>
<th>Breed</th>
<th>Average Score</th>
</tr>";
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>". "" ."". $row['Owner']. "</td>";
echo "<td>". "" ."<a href= mailto:$row[Email]>$row[Email]</a></td>";
echo "<td>". "" . $row["Name"] . "</td>";
echo "<td>". "" . $row["breed_name"] . "</td>";
echo "<td>". "" . $row["avg_score"] . "</td>";
echo "</tr>";
}
echo "</table>";
$conn->close();
?>
<!-- connection message will fade away-->
<script>
$( document ).ready( readyFn );
$(function() {
$('#echo').fadeOut(1000);
});
</script>
</body>
</html>
my $_GET method on the other page is now taking the number but it's still not displaying the owner's details and no errors or anything. I don't know what's wrong with the code. A would appreciate any advice regarding code, formatting, etc.
<html>
<head>
<title>OwnerDetail</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
window.onload = function()
{
timedHide(document.getElementById('co'), 10);
}
function timedHide(element, seconds)
{
if (element) {
setTimeout(function() {
element.style.display = 'none';
}, seconds*1000);
}
}
</script>
<?php
require 'Navbar.php';
?>
<?php
include './connection.php';
?>
<?php
$id = $_GET['id']; // Collecting data from query string
if (!is_numeric($id)) { // Checking data it is a number or not
echo "Data Error";
exit;
}
$count=$dbo->prepare("SELECT * FROM owners WHERE id=:id");
$count->bindParam(":id",$id,PDO::PARAM_INT,3);
if($count->execute()){
echo " Success ";
$row = $count->fetch(PDO::FETCH_OBJ);
echo "<table>";
}
echo "
<tr bgcolor='#f1f1f1'><td><b>Name</b></td><td>$row->name</td></tr>
<tr><td><b>Class</b></td><td>$row->class</td></tr>
<tr bgcolor='#f1f1f1'><td><b>Mark</b></td><td>$row->mark</td></tr>
<tr><td><b>Address</b></td><td>$row->address</td></tr>
<tr bgcolor='#f1f1f1'><td><b>Image</b></td><td>$row->img</td></tr>
";
echo "</table>";
?>
<script>
$( document ).ready( readyFn );
$(function() {
$('#echo').fadeOut(1000);
});
</script>
</body>
</html>
You really should consider doing this:
Replace the ancient jQuery
Simplify the PHP which is already producing invalid HTML
Ajax the data only
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function() {
$("#ownerTable a.owner").on("click", function(e) {
e.preventDefault(); // stop link
const ownerDetails = $.get(this.href, function(data) {
$("#output").html(data)
});
});
});
<script>
and have
<table>
<thead>
<tr>
<th>Owner</th>
<th>Email</th>
<th>Dog</th>
<th>Breed</th>
<th>Average Score</th>
</tr>
</thead>
<tbody id="ownerTable">
<? while($row = mysqli_fetch_assoc($result)) { ?>
<tr>
<td>
<a class="owner" href="OwnerDetails.php?id=<?= $row['id'] ?>"><?= $row['Owner'] ?></a>
</td>
<td>
<?= $row[Email] ?>
</td>
<td>
<?= $row["Name"] ?>
</td>
<td>
<?= $row["breed_name"] ?>
</td>
<td>
<?= $row["avg_score"] ?>
</td>
</tr>
<? } ?>
</tbody>
<tbody id="output"></tbody>
</table>
where Ownerdetails.php now looks like
<?php
$id = $_GET['id']; // Collecting data from query string
if (!is_numeric($id)) { // Checking data it is a number or not
echo "<tr><td>Data Error</td></tr>";
exit;
}
$count=$dbo->prepare("SELECT * FROM owners WHERE id=:id");
$count->bindParam(":id",$id,PDO::PARAM_INT,3);
if($count->execute()){
$row = $count->fetch(PDO::FETCH_OBJ);
echo "
<tr bgcolor='#f1f1f1'><td><b>Name</b></td><td>$row->name</td></tr>
<tr><td><b>Class</b></td><td>$row->class</td></tr>
<tr bgcolor='#f1f1f1'><td><b>Mark</b></td><td>$row->mark</td></tr>
<tr><td><b>Address</b></td><td>$row->address</td></tr>
<tr bgcolor='#f1f1f1'><td><b>Image</b></td><td>$row->img</td></tr>";
}
?>

AJAX not functioning

I have been staring at this for literally two hours trying to fix it. Any help would be appreciated. For some reason the table isn't being loaded when the button is clicked.
Here's the relevant part of my head:
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css" />
</head>
This is my table:
<div class="container">
<div class="midtxt">
<div id = "transactions-sav" style="margin-top: 0;">
<h2>Most Recent Transactions</h2>
<table>
<thead>
<tr>
<th>Username</th>
<th>Amount</th>
<th>Time & Date</th>
<th>Account Type</th>
</tr>
</thead>
<tbody>
<div id="trans-div">
</div>
</tbody>
</table>
<hr />
</div>
</div>
<a class="btn light-blue waves-effect waves-light table-end" id="trans-more" style="margin-top: 35px;">Load More Transactions</a>
</div>
This is my Ajax transmitter:
<script>
$(document).ready(function() {
let transCount = 20;
$('#trans-more').on('click', function() {
transCount += 20;
console.log('click');
console.log(transCount);
$('#trans-div').load('includes/loadtranshistajax.inc.php', {transNewCount: transCount,user_id: <?php echo $_SESSION['user_id']; ?>}, function() {
console.log('callback');
});
});
console.log('test1');
});
</script>
This is my PHP script for generating the table. It is worth noting that initialize() starts a session.:
<?php
require_once 'dbc-stu.inc.php';
require_once 'initialize.inc.php';
require_once 'app/transactions/transhist.inc.php';
initialize();
initialize_secure();
//Import the count
$limit = $_POST['transNewCount'];
$userID = $_SESSION['user_id'];
$sql = "SELECT * FROM transactions WHERE trans_targetID ='$userID' ORDER BY trans_time DESC LIMIT $limit";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
while ($row = mysqli_fetch_assoc($result)) {
echo '<tr>';
foreach ($row as $key => $value) {
if ($key === 'trans_time') {
$time = $value;
date_default_timezone_set("America/Los_Angeles");
$time = date("F j, Y, g:i a",$time);
} elseif ($key === 'trans_amount') {
$amnt = $value;
} elseif ($key ==='trans_targetID') {
$username = idToUsername($value);
} elseif ($key === 'trans_accType') {
$accType = $value;
}
}
echo '<td>' . $username . '</td>';
echo '<td>' . $amnt . '</td>';
echo '<td>' . $time . '</td>';
echo '<td>' . $accType . '</td>';
echo '</tr>';
}
Edit, thanks a lot everybody. I'm fairly new to the web development community, so it's cool to see everyone help out!
Remove div tag from tag and add id in tbody attribute as below.
<tbody id="trans-div"></tbody>
Put the php code<?php echo $_SESSION['user_id']; ?> inside a <script> tag into double quote as it's causing the SyntaxError which break` your script code.
That's why you are not able to view XHR into console
Try the following:
$('#trans-div').load('includes/loadtranshistajax.inc.php', {transNewCount: transCount,user_id: "<?php echo $_SESSION['user_id']; ?>"}, function() {
console.log('callback');
});

applying search or filter to table with pagination

hello kind sirs can you help me with this code. What i try to do is when i type something in the search box, ex. pending it will show the 5 pending reservation per page(5 rows of pending reservation). but when i try it, it shows all the pending reservation which is more than 10.
here is the image
i try something like this.. but it shows nothing
$query = "SELECT * FROM reservations WHERE CONCAT(firstname, lastname, reservationstatus)LIKE '%".$valueToSearch."%' LIMIT " . $this_page_first_result . ',' . $results_per_page";
Here is the whole code
<?php
error_reporting(E_ALL & ~E_NOTICE);
error_reporting(E_ERROR | E_PARSE);
session_start();
?>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "srdatabase";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$results_per_page = 5;
$select= "SELECT * FROM reservations";
$result = mysqli_query($conn, $select);
$number_of_results = mysqli_num_rows($result);
if(!isset($_GET['page']))
{
$page = 1;
}
else
{
$page = $_GET['page'];
}
$this_page_first_result = ($page-1)*$results_per_page;
$sql = "SELECT * FROM reservations LIMIT " . $this_page_first_result . ',' . $results_per_page;
$result = mysqli_query($conn, $sql);
$number_of_pages = ceil($number_of_results/$results_per_page);
?>
<div id="paging-div">
<?php
for($page=1;$page<=$number_of_pages;$page++)
{
echo '<a id="pagingLink" href="adminControl.php?page=' . $page . '">' . $page . '</a>';
}
?>
<?php
if(isset($_POST['search']))
{
$valueToSearch = $_POST['valueToSearch'];
$query = "SELECT * FROM reservations WHERE CONCAT(firstname, lastname, reservationstatus)LIKE '%".$valueToSearch."%'";
$search_result = filterTable($query);
}
else
{
$query = "SELECT * FROM reservations";
$search_result = filterTable($query);
}
function filterTable($query)
{
$conn = mysqli_connect("localhost", "root", "", "srdatabase");
$filter_Result = mysqli_query($conn, $query);
return $filter_Result;
}
?>
</div>
<!DOCTYPE html>
<html>
<head>
<title>Admin Control</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div class="topnav" id="myTopnav">
Home
Speakers
About
Contact
Reservation
Sign Out
<?php echo $_SESSION['firstname']; ?>
Sign Up
Sign In
Admin control
☰
</div>
<br>
<br>
<br>
<br>
<h4 style="padding-left:10px; text-align:center;">Reservation List</h4>
<hr>
<form action="adminControl.php" method="POST">
<input type="text" name="valueToSearch" placeholder="type a value">
<input type="submit" name="search" value="Filter">
</form>
<br>
<br>
<div style="overflow-x:auto;">
<table class="reservations-table">
<tr>
<th class="thFirstName">First Name</th>
<th class="thLastName">Last Name</th>
<th class="thEmailAddress">Email Address</th>
<th class="thContactNumber">Contact Number</th>
<th class="thSpeaker">Speaker</th>
<th class="thTopic">Topic</th>
<th class="thLocation">Location</th>
<th class="thAudience">Audience</th>
<th class="thCount">Count</th>
<th class="thTime">Time</th>
<th class="thDate">Date</th>
<th class="thAction">Reservation Date</th>
<th class="thAction">Status</th>
<th class="thAction">Action</th>
<th class="thAction">Action</th>
</tr>
<?php while($row = mysqli_fetch_array($search_result)):?>
<tr>
<td><?php echo $row['firstname'];?></td>
<td><?php echo $row['lastname'];?></td>
<td><?php echo $row['emailaddress'];?></td>
<td><?php echo $row['contactnumber'];?></td>
<td><?php echo $row['speaker'];?></td>
<td><?php echo $row['topic'];?></td>
<td><?php echo $row['location'];?></td>
<td><?php echo $row['audience'];?></td>
<td><?php echo $row['count'];?></td>
<td><?php echo $row['time'];?></td>
<td><?php echo $row['date'];?></td>
<td><?php echo $row['reservationdate'];?></td>
<td><?php echo $row['reservationstatus'];?></td>
</tr>
<?php endwhile;?>
</table>
</form>
</div>
<?php
$epr='';
$msg='';
if(isset($_GET['epr']))
$epr=$_GET['epr'];
if($epr=='delete')
{
$id=$_GET['id'];
$delete=mysqli_query($conn, "DELETE FROM reservations WHERE id=$id");
if($delete)
header('location:adminControl.php');
else
$msg='Error :'.mysqli_error();
}
?>
<?php
$epr='';
$msg='';
if(isset($_GET['epr']))
$epr=$_GET['epr'];
if($epr=='approve')
{
$id=$_GET['id'];
$approve=mysqli_query($conn, "UPDATE reservations SET reservationstatus='approved' WHERE id=$id");
header('location:adminControl.php');
}
?>
<script>
function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
</script>
<script>
function ifAdmin()
{
document.getElementById("signIn").style.display = "none";
document.getElementById("signUp").style.display = "none";
document.getElementById("signOut").style.display = "block";
document.getElementById("adminControl").style.display = "block";
}
</script>
<script>
function ifNotAdmin()
{
document.getElementById("signIn").style.display = "none";
document.getElementById("signUp").style.display = "none";
document.getElementById("signOut").style.display = "block";
document.getElementById("adminControl").style.display = "none";
}
</script>
<script>
function ifNotLogin()
{
document.getElementById("user").style.display = "none";
document.getElementById("signOut").style.display = "none";
document.getElementById("adminControl").style.display = "none";
}
</script>
<?php
if (isset($_SESSION['signedIn']) && $_SESSION['signedIn'] == true)
//if login
{
if($_SESSION['type'] == 1)
{
echo "<script type='text/javascript'>ifAdmin();</script>";
}
elseif($_SESSION['type'] == 0)
{
echo "<script type='text/javascript'>ifNotAdmin();</script>";
}
}
//if not login
else
{
echo "<script type='text/javascript'>ifNotLogin();</script>";
}
?>
<div id="footer" class="push">Copyright 2017</div>
</body>
</html>
... when i try it, it shows all the pending reservation which is more than 10.
That's because when you hit 2nd, 3rd, ... pages(after navigating from the 1st page), the $_POST array would be empty i.e. $_POST['search'] won't be set, and that's why else{...} part of the code will get executed every time you navigate to 2nd, 3rd, ... pages. Since you're not sending any sensitive data with the form, use GET instead of POST in the method attribute of the form, like this:
<form action="..." method="get">
and get the user inputted data like this:
if (isset($_GET['search'])) {
$valueToSearch = $_GET['valueToSearch'];
...
Subsequently, you need to attach that search query in each of your pagination links, so that the search query would be available when you hop from page to page.
// your code
<?php
for($page=1;$page<=$number_of_pages;$page++)
{
echo "<a id='pagingLink' href='adminControl.php?page=" . $page . "&valueToSearch=". urlencode($_GET['valueToSearch']) ."&search'>" . $page . "</a>";
}
?>
// your code

echo two tables issues required to post twice (mysql, php)

I finally get reviews to work, which will allow user to post their review about the product and display them in a review page with product details, however I can't get it to work perfectly. When a user posts their review, it will update in the table but only the second post will show up.
The following image is from the test i was running,
Before posting a review
After posting the first review
After posting the second review
As the images display, the first review will never show up, only starting from the second and above,
Here my code for review page updated with full code
<?php
if (!isset($_SESSION)) {session_start();} //start session
if (!isset($_SESSION['client_ID'])) {
//echo "<script>alert('not logged in');</script>";
header("Location: index.html" );
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="keywords" content="Games, Gaming, PS4, PS3, XBOX, Video games">
<meta name="description" content="Games 4 You">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Games 4 You</title>
<link rel="stylesheet" type="text/css" href="Styles/ProductsStyle.css">
<!-- javascript/jQuery -->
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<!--Add the following script at the bottom of the web page (before </body></html>)
Support system using MyLiveChat.com
-->
<script type="text/javascript" async="async" defer="defer" data-cfasync="false" src="https://mylivechat.com/chatinline.aspx?hccid=42206151"></script>
<script>// disable zoom to keep image fit and always in position
document.firstElementChild.style.zoom = "reset";
// the above script will disable zoom in and out
</script>
<script type="text/javascript">
// this will auto change the background image to the following 7 images which are in the root Images/
// this is set to change every five second
// declare list of backgrounds
var images = ['bg-01.jpg', 'bg-02.jpg', 'bg-03.jpg', 'bg-04.jpg', 'bg-05.jpg', 'bg-06.jpg', 'bg-07.jpg'];
// declare function that changes the background
function setRandomBackground() {
// choose random background
var randomBackground = images[Math.floor(Math.random() * images.length)];
// set background with jQuery
$('body').css('background-image', 'url("Images/' + randomBackground + '")');
}
// declare function that sets the initial background, and starts the loop.
function startLoop() {
// Set initial background.
setRandomBackground();
// Tell browser to execute the setRandomBackground every 5 seconds.
setInterval(setRandomBackground, 5 * 1000);
}
// One the page has finished loading, execute the startLoop function
$(document).ready(startLoop);
</script>
<header id="header">
<div class="container">
<center><img src="Images/Title.png" alt="Title"></div>
</center>
</header>
<center>
<nav>
<?php
echo "<p> Welcome ".$_SESSION['client_name']."</p>";
//create connection
$con = new mysqli("localhost", "student", "student", "cib4003_h00233671_at");
if ($con->connect_errno) { //failed
echo "Failed to connect to MySQL: (" . $con->connect_errno . ") " . $con->connect_error;
}?>
<div class="wrapper">
<ul id="category" >
<li>Home</li>
<li>Products</li>
<li>View Cart</li>
<li>About</li>
<li>Settings</li>
<li>Logoff</li>
</ul>
</nav>
</div>
</center>
<main>
<h3>Available Products</h3>
<?php
$product = $_GET["RID"];
$_SESSION["product_name_RID"] = $_GET["RID"];
$sql="SELECT * FROM products,reviews WHERE products.Product_Name = '$product' AND reviews.Product_Name = '$product'";
//$sql="SELECT * FROM reviews WHERE Product_Name = '$product'";
// $sql="SELECT * FROM pizza,pizzacart WHERE pizza.Pizza_ID=pizzacart.Pizza_ID AND pizzacart.client_ID=".$_SESSION['client_ID'];
//echo "connected to DB";
//run SQL query
$result = mysqli_query($con,$sql);
//output result
if(mysqli_num_rows($result)==0) //no records found
{
$sql="SELECT * FROM products WHERE Product_Name = '$product'";
$result = mysqli_query($con,$sql);
// echo "<p>no records in DB".mysqli_num_rows($result)."</p>";
// echo "<p><a href=products.php></a>";
// link has been disable because i am using the <a for something else so i can't force the image to be in the center when using <a
// so the result will only be image that tell the customers no products found click all or search with different data
?>
<table class="table-style-one">
<tr>
<th>Product Image</th>
<th>Product Name</th>
<th>Description</th>
<th>Product Type</th>
<th>Console Type</th>
</tr>
<?php
while($row = mysqli_fetch_array($result)) { //loops through records
echo "<tr>";
echo "<td><img src='".$row['picture']."'/>";
echo "<td>".$row['Product_Name']."</td>";
echo "<td>".$row['Description']." <center><b><br>".$row['Trailer']."<br></b></center></td>";
echo "<td>".$row['Product_Type']."</td>";
echo "<td>".$row['Console_Type']."</td>";
echo "</tr>";
}
//end of loop
echo "</table>";
echo "<p>No Reviews available for this product.<br> To post a review of this product, fill up the below form.</p>";
//end of else
}
else
{
?>
<table class="table-style-one">
<tr>
<th>Product Image</th>
<th>Product Name</th>
<th>Description</th>
<th>Product Type</th>
<th>Console Type</th>
</tr>
<?php
while($row = mysqli_fetch_array($result)) { //loops through records
echo "<tr>";
echo "<td><img src='".$row['picture']."'/>";
echo "<td>".$row['Product_Name']."</td>";
echo "<td>".$row['Description']." <center><b><br>".$row['Trailer']."<br></b></center></td>";
echo "<td>".$row['Product_Type']."</td>";
echo "<td>".$row['Console_Type']."</td>";
echo "</tr>";
echo "<br>";
?>
<?php
while($row = mysqli_fetch_array($result)) {
echo "<table class=table-style-one align=center>";
// echo "<tr><th>Review ID</th><td>".$row['Review_ID']."</td></tr>";
echo "<tr><th>Review By:</th><td>".$_SESSION['client_name']."</td></tr>";
echo "<tr><th>Review Title</th><td>".$row['Review_Title']."</td></tr>";
echo "<tr><th>Rate:</th><td>".$row['Review_Rate']."/5</td></tr>";
echo "<tr><th>Review</th><td colspan=2>".$row['Review']."</td></tr>";
echo "<tr><th>Submitted On</th><td>".$row['Review_Date']."</td></tr>";
echo "<br>";
?>
<?php
}
//end of loop
echo "</table>";
//end of else
}
}
?>
<table class="table-style-one" align="center">
<tr>
<form method="POST" action="submitreview.php">
<!--<th>Product Name:</th><td> <input type="text" size="30" id="ReviewTitle" name="ReviewTitle" pattern=".{5,}" required title="5 characters minimum" placeholder="Review Title"></td> -->
<th>Review Title:</th><td> <input type="text" required size="30" id="ReviewTitle" name="ReviewTitle" pattern=".{5,}" required title="5 characters minimum" placeholder="Review Title"> </td>
<th>Rate: </th>
<td>
<select name="Review_Rate" required>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</td>
<tr>
<td colspan="4">
<textarea name="WriteReview" id="WriteReview" required rows="10" cols="50" wrap="physical" placeholder="Write your Review here" style="margin: 0px; width: 437px; height: 150px;"></textarea>
</td>
</tr>
<td align="center" colspan="2"><input type="submit" value="submit"></td>
<td colspan="2"><input type="Reset"></td>
</form> </tr>
</table>
</h2>
<br>
<br>
<br>
</main>
</body>
<footer>
<p>Made by Humaid Al Ali - H00233671</p>
<div id="google_translate_element"></div><script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.HORIZONTAL, multilanguagePage: true}, 'google_translate_element');
}
</script><script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
</footer>
</html>
and here the php file where I insert the review into the table
<?php
if (!isset($_SESSION)) {session_start();} //start session
if (!isset($_SESSION['client_ID'])) {
//echo "<script>alert('not logged in');</script>";
header("Location: index.html" );
}
?>
<?php
//new connection
$con = new mysqli("localhost", "student", "student", "cib4003_h00233671_at");
if ($con->connect_errno) { //failed
echo "Failed to connect to MySQL: (" . $con->connect_errno . ") " . $con->connect_error;
}
//success
//if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// run sql
$sql ="INSERT INTO `cib4003_h00233671_at`.`reviews`(`Review_ID`, `Product_Name`, `client_ID`, `Review_Title`, `Review_Rate`, `Review`) VALUES (NULL, '".$_SESSION['product_name_RID']."', '".$_SESSION['client_ID']."', '".$_POST["ReviewTitle"]."', '".$_POST['Review_Rate']."', '".$_POST['WriteReview']."');";
if ($con->query($sql) === TRUE) {echo "<h3> New record created successfully</h3>";
header('Location: '. $_SERVER['HTTP_REFERER'] );
} else {
echo "Error : " . $sql . "<br>" . $con->error;
}
$con->close();
?>
Problem:
As the images display, the first review will never show up, only starting from the second and above
That's because you're fetching the first row which includes the first review but you don't display it, rather you starting fetching next reviews and display them. Look at the two conditions in while block inside the else block.
Solution:
To display reviews, you should do something like this:
<?php
// your code
if(mysqli_num_rows($result)==0){
// your code
}else{
echo "<table class='table-style-one'>";
echo "<tr>";
echo "<th>Product Image</th>";
echo "<th>Product Name</th>";
echo "<th>Description</th>";
echo "<th>Product Type</th>";
echo "<th>Console Type</th>";
echo "</tr>";
// fetch first row, which also contains first review
$row = mysqli_fetch_array($result);
echo "<tr>";
echo "<td><img src='" . $row['picture'] . "'/>";
echo "<td>" . $row['Product_Name'] . "</td>";
echo "<td>" . $row['Description'] . "<center><b><br>" . $row['Trailer'] . "<br></b></center></td>";
echo "<td>" . $row['Product_Type'] . "</td>";
echo "<td>" . $row['Console_Type'] . "</td>";
echo "</tr>";
echo "</table>";
echo "<table class=table-style-one align=center>";
echo "<tr>";
echo "<th>Review ID</th>";
echo "<th>Review By:</th>";
echo "<th>Review Title</th>";
echo "<th>Rate:</th>";
echo "<th>Review</th>";
echo "<th>Submitted On</th>";
echo "</tr>";
do{
// display first review and then fetch rest of the reviews
echo "<tr>";
echo "<td>" . $row['Review_ID'] . "</td>";
echo "<td>" . $_SESSION['client_name'] . "</td>";
echo "<td>" . $row['Review_Title'] . "</td>";
echo "<td>" . $row['Review_Rate'] . "/5</td>";
echo "<td colspan=2>" . $row['Review'] . "</td>";
echo "<td>" . $row['Review_Date'] . "</td>";
echo "</tr>";
}while($row = mysqli_fetch_array($result));
echo "</table>";
?>
</table>
<?php
}
// your code
?>
The problem looks to me to be in your SQL query. It looks as though your SQL query should actually be doing a join on the related column to bring together data across two different tables
$sql="SELECT *
FROM products AS p,
JOIN reviews AS r
ON p.Product_Name = r.Product_Name
WHERE products.Product_Name = '$product'";
But I think the easiest solution would be to run another query within the table output loop where you get the reviews for the product name you are currently outputting and loop over those.

Put MySQL request result in table

<?PHP
?>
<html>
<head>
<title></title>
<link rel="stylesheet" href="one.css" type="text/css">
</head>
<?
include_once "db.php";
$result = mysql_query("SELECT * FROM products WHERE product_type='weddingdressaline' ORDER BY user_id");
{
echo "<table width='100%' border='5' bordercolor='#860071' cellspacing='5' cellpadding='5'>";
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result))
{
echo "<tr>";
$i = 0;
while ($i < 3)
{
echo '<td><table width="100%" border="0" cellspacing="0" cellpadding="0" BGCOLOR="#AA99C5"><TR><TD><div class="container"><img src="showimage.php?user_id=' . $row["user_id"] . '" ALIGN="CENTER" /></div></td><tr><td><CENTER><STRONG>' . $row['price'] . '</STRONG></td></TABLE>';
$i++;
}
echo "</tr>";
}
} else {
echo "<tr><td colspan='" . ($i + 1) . "'>No Results found!</td></tr>";
}
echo "</table>";
}
?>
The code is suppose to put one item into one column. Unfortunately its placing one result for the entire row. If anyone has any ideas how to fix this please help.
You have some access brackets in your code:
$result = mysql_query("SELECT * FROM products WHERE product_type='weddingdressaline' ORDER BY user_id");
{ <===
echo "<table width='100%' border='5' bordercolor='#860071' cellspacing='5' cellpadding='5'>";
[....]
echo "</table>";
} <===
First of all please learn some clean coding standards for everyones sake:
http://drupal.org/coding-standards
The second problem is that your are outputting this in the wrong. Trying to use tables for one (use divs) is just poor markup these days. All your styles should be in your CSS, not embedded on the page.
Here is your greatly improved markup. You use CSS to change how it is displayed on the page, not a table structure.
<html>
<head>
<title></title>
<link rel="stylesheet" href="one.css" type="text/css">
</head>
<body>
<?php
include_once "db.php";
$result = mysql_query("SELECT * FROM products WHERE product_type = 'weddingdressaline' ORDER BY user_id");
echo '<div class="productTable">';
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_object($result)) {
echo '
<div class="container">
<div class="productImage">
<a href="viewproduct.php?user_id=' . $row->user_id . '">
<img src="showimage.php?user_id=' . $row->user_id . '" align="center" />
</a>
</div>
<div class="price">' . $row->price . '</div>
</div>';
}
}
else {
echo '<div class="container"><div class="noResults">No Results found!</div></div>';
}
echo "</div>";
?>
</body>
</html>

Categories