Populate table based on selected dropdown value - php

I want to know where to put the condition to display data in a table after I select the value from a dropdown list.
Both have the same id (dropdown and table).
php table
<html>
<head>
</head>
<body>
<?php
$con=mysqli_connect("localhost","root","root","company");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT employees.id,employees.jobs FROM employees WHERE employees.jobs in ("programmer","hr","qa")";
if ($result=mysqli_query($con,$sql)){
?>
<label for="y">Select the job:</label>
<select name="loads" id="loads" onchange="">
<?php while($ri = mysqli_fetch_array($result)) {
?>
<option value="<?php echo $ri['id'];?>" > <?php echo $ri['jobs']; ?> </option>
<?php
}
}
?>
</select>
<table class="striped" border="1" align="center" id="demo">
<tr class="header">
<td align="center"><b>Name</b></td>
</tr>
<?php
$con=mysqli_connect("localhost","root","root","company");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql2="SELECT employees.id,employees.name FROM employees WHERE employees.jobs in ("programmer","hr","qa")";
if ($result=mysqli_query($con,$sql2)){
// Fetch one and one row
while ($row=mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row["name"] . " " . "</td>";
echo "</tr>";
}
}
mysqli_close($con);
?>
</table>
</body>
</html>

If you mean: you want to something happens to your table when an item get selected in dropdown list(select tag). then it is not possible through php because php codes compiled once after each load on a page and it doesnt work live!
so you have to use JQUERY and AJAX to do that.
if this is what you searching for, reply me so i can help you.
by the way you dont need to connect 2 times into database and run the same query, i just edited your code a little bit:
<html>
<head>
<title></title>
</head>
<body>
<?php $con = mysqli_connect("localhost","root","root","company");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT * FROM employees WHERE employees.jobs in ("programmer","hr","qa")";
$result = mysqli_query($con, $sql);
if ($result) { ?>
<label for="y">Select the job:</label>
<select name="loads" id="loads" onchange="">
<?php while($ri = mysqli_fetch_array($result)) { ?>
<option value="<?php echo $ri['id'];?>" > <?php echo $ri['jobs']; ?> </option>
<?php
}
}
?>
</select>
<table class="striped" border="1" align="center" id="demo">
<tr class="header">
<td align="center"><b>Name</b></td>
</tr>
<?php
// Fetch one and one row
while ($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row["name"] . " " . "</td>";
echo "</tr>";
}
mysqli_close($con);
?>
</table>
</body>
</html>

Related

Displaying mysql results inside a table using php

I have a very simple webpage setup for delivering media content from a mysql database, but after my hosts upgraded my server, the site went down.
It was created many years ago so this was to be expected.
I have attempted to update my code to current standards, but I am still not getting any results from my query.
The page opens but does not return anything past the header.
I have run the code through a couple of php syntax checkers and no faults are detected.
could somebody possible suggest where I am going wrong.
I have not done any coding for 7yrs or so, so finding the fault is taking way longer than it should.
Here is the full code from my index.php
<?php
include 'header.php';
include 'welcome.php';
include 'musicDb.php';
include 'analyticstracking.php';
/* MAIN QUERY */
$query_recordset1 = "SELECT * FROM setinfo ORDER BY setid DESC";
$recordset1 = mysqli_query($query_recordset1, $musicDb) or die(mysqli_error());
$row_recordset1 = mysqli_fetch_assoc($recordset1);
$totalRows_recordset1 = mysqli_num_rows($recordset1);
?>
<tr>
<td>
<table align="center">
<!-- LOOP THROUGH RESULTS AND DISPLAY ALL RESULTS -->
<?php do { ?>
<tr CLASS="data_left" >
<td><a href="<?php echo $row_recordset1['id'];?>.php"><img width="200" HEIGHT="200" src="<?php echo $row_recordset1['artwork']; ?>" /></td>
<td>
<table>
<tr><td><a href="player.php?TargetSet=<?php echo $row_recordset1['setid'];?>"><?php echo $row_recordset1['setname'];?></td></tr>
<tr><td><?php echo $row_recordset1['dj'] ; ?> </td></tr>
<tr><td><?php echo $row_recordset1['bpm'] ; ?>bpm <?php echo $row_recordset1['genre'] ; ?> (<?php echo $row_recordset1['era'] ;?>) </td></tr>
<tr><td><?php echo $row_recordset1['length'] ; ?> </td></tr>
<tr><td><?php echo $row_recordset1['date'] ; ?> </td></tr>
</table>
</td>
</tr>
<tr height="50" ><td colspan="4"><img src="images/lineindex.png" /></td></tr>
<tr height="50" ></tr>
<!-- END LOOP -->
<?php } while ($row_recordset1 = mysqli_fetch_assoc($recordset1)); ?>
</table>
<!-- LINK TO FOOTER -->
<?php include 'footer.php'; ?>
I also created a test file to check my raw query is still working, and it does retrun the data.
<?php
// Create connection
$conn = new mysqli("*****", "*****", "*****", "*****");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM setinfo ORDER BY setid DESC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo
" " . $row["artwork"].
" " . $row["setid"].
" " . $row["dj"].
" " . $row["setname"].
": " . $row["bpm"].
": " . $row["length"].
": " . $row["date"].
": " . $row["file"].
": " . $row["filesize"].
"<br><br>";
}
} else {
echo "0 results";
}
$conn->close();
?>

PHP not printing database as table

I am attempting to print out mySQL database into a html table. I have watched many tutorials on how to do this but am unsure as to how I refer to the html table in my php code. The information gets printed fine and connects to the database but for some reason it isn't output in the table format.
<?php
$conn = mysqli_connect('localhost', 'Admin', 'admin1', 'info');
if (!$conn) {
echo "Connection failed:" . mysqli_connect_error();
}
//Writing query for database.
$sql = "SELECT `First Name`,`Last Name`,Emails,`Date Created` FROM clientinfo ORDER BY `Date Created`";
//Querying and getting results
$result = mysqli_query($conn, $sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["First Name"] . "</td></tr>" . $row["Last Name"] . "</td></tr>"
. $row["Emails"] . "</td></tr>" . $row["Date Created"] . "</td></tr>";
}
echo "</table>";
} else {
echo "0 result";
}
//Fetch resulting rows as an array
$informed = mysqli_fetch_all($result, MYSQLI_ASSOC);
// Freeing result from the memory.
mysqli_free_result($result);
mysqli_close($conn);
?>
<!DOCTYPE html>
<html lang="en-US">
<head>
<div class="Contained">
<div class="row">
<?php foreach ($informed as $inform) { ?>
<div class="col s6 medium-3">
<div class="card z-depth-0">
<div class="card-content center">
<h6><?php echo htmlspecialchars($inform['First Name']); ?></h6>
<div><?php echo htmlspecialchars($inform['Last Name']); ?></div>
</div>
<div class="card-action right-align">
<a class="brand-text" href="#">More Info
</div>
</div>
</div>
<?php } ?>
</div>
</div>
<title> Email and Name List </title>
</head>
<body>
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Emails</th>
<th>Date Created</th>
</tr>
</table>
</body>
</html>
Output in browser gyazo:
You must change code for output all table in php like:
<body>
<?php
$conn = mysqli_connect('localhost', 'Admin', 'admin1', 'info');
if (!$conn){
echo "Connection failed:" . mysqli_connect_error();
}
//Writing query for database.
$sql = "SELECT `First Name`,`Last Name`,Emails,`Date Created` FROM clientinfo ORDER BY `Date
Created`";
//Querying and getting results
$result = mysqli_query($conn,$sql);
if ($result->num_rows>0){
echo '
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Emails</th>
<th>Date Created</th>
</tr>';
while($row = $result->fetch_assoc()){
echo "<tr> ";
echo "<td>" . $row["First Name"] . "</td>";
echo "<td>" . $row["Last Name"] . "</td>";
echo "<td>" . $row["Date Created"] . "</td>";
echo "</tr> ";
}
echo"</table>";
}
else{
echo "0 result";
}
//Fetch resulting rows as an array
$informed = mysqli_fetch_all($result, MYSQLI_ASSOC);
// Freeing result from the memory.
mysqli_free_result($result);
mysqli_close($conn);
?>
</body>
Another question are you sure is $row["First Name"] and not $row["First_Name"]?
Last tip learn how prepare stm for prevent sql inject
Based on your code, you are trying to print the table before the actual table is defined below. You can try something like this:
<?php
$conn = mysqli_connect('localhost', 'Admin', 'admin1', 'info');
if (!$conn){
echo "Connection failed:" . mysqli_connect_error();
}
//Writing query for database.
$sql = "SELECT `First Name`,`Last Name`,Emails,`Date Created` FROM clientinfo ORDER BY `Date Created`";
//Querying and getting results
$result = mysqli_query($conn,$sql);
$informed = mysqli_fetch_all($result, MYSQLI_ASSOC);
?>
<!DOCTYPE html>
<html lang="en-US">
<head>
<div class="Contained">
<div class="row">
<?php foreach($informed as $inform){?>
<div class="col s6 medium-3">
<div class="card z-depth-0">
<div class="card-content center">
<h6><?php echo htmlspecialchars($inform['First Name']); ?></h6>
<div><?php echo htmlspecialchars($inform['Last Name']);?></div>
</div>
<div class="card-action right-align">
<a class="brand-text" href="#">More Info</div>
</div>
</div>
<?php }?>
</div>
</div>
<title> Email and Name List </title>
</head>
<body>
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Emails</th>
<th>Date Created</th>
</tr>
<?php
if ($result->num_rows>0) {
while($row = $result->fetch_assoc()){
echo "<tr><td>" . $row["First Name"] . "</td><td>" . $row["Last Name"] . "</td><td>" . $row["Emails"] . "</td><td>" . $row["Date Created"] . "</td></tr>";
}
} else {
echo "<tr><td rowspan=\"5\">0 result</td></tr>";
}
?>
</table>
</body>
<?php
// Freeing result from the memory.
mysqli_free_result($result);
mysqli_close($conn);
?>

Search tables from SQL and show their data on page

I've been trying to find an easy way for this. A search (dropdown menu) of all tables in mysql, and show their content when I click the table I want to show on the page. Instead of showing just every table on the page I thought it can be easier? Any help would be appreciated! My code so far:
<?php
$host = "localhost";
$user = "heijsdb_user";
$pass = "maus";
$db_name = "heijsdb";
//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);
//test if connection failed
if(mysqli_connect_errno()){
die("connection failed: "
. mysqli_connect_error()
. " (" . mysqli_connect_errno()
. ")");
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
echo "borsten HFP controle";
$result = mysqli_query($connection,"SELECT * FROM borstenHFPcontrole");
$all_property = array(); //declare an array for saving property
//showing property
echo '<table class="data-table w3-table-all" border="2px">
<tr class="data-heading">'; //initialize table tag
while ($property = mysqli_fetch_field($result)) {
echo '<td>' . $property->name . '</td>'; //get field name for header
array_push($all_property, $property->name); //save those to array
}
echo '</tr>'; //end tr tag
//showing all data
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>'; //get items using property value
}
echo '</tr>';
}
echo "</table>";
////////////////////////////////////////////////////////////////////////////////////////////////////////////
This is pretty much the idea, you can play from here and adapt it to your solution. Sorry I used my way, I prefer PHP template style when embedding in HTML. ;)
$host = "localhost";
$user = "heijsdb_user";
$pass = "maus";
$db_name = "heijsdb";
//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);
//test if connection failed
if(mysqli_connect_errno()){
die("connection failed: "
. mysqli_connect_error()
. " (" . mysqli_connect_errno()
. ")");
}
//check if the form was submitted
$table = filter_input(INPUT_POST, 'table', FILTER_SANITIZE_STRING);
?>
<html>
<head>
<title>showing table content on user action</title>
</head>
<body>
<div>
<form id="form-menu" method="post">
<label for="select-menu">Choose a table</label>
<select id="select-menu" name="table">
<option></option>
<?php
$result = mysqli_query($connection,"SELECT table_name FROM information_schema.tables where table_schema='test'"); // <-- the table_schema field here is your database name, change 'test' for yours
while ($row = mysqli_fetch_array($result)) : $selected = $row['table_name'] == $table ? 'selected' : ''; ?>
<option value="<?php echo $row['table_name'] ; ?>" <?php echo $selected; ?>><?php echo $row['table_name'] ; ?></option>
<?php endwhile; ?>
</select>
</form>
<hr>
<div>
<?php if (empty($table)) : ?>
<h3>Please select a table to show its content</h3>
<?php else : ?>
<h3>Content for the table `<?php echo $table; ?>`</h3>
<?php
$result = mysqli_query($connection,"SELECT * FROM `{$table}`");
$all_property = []; //declare an array for saving property
?>
<!-- showing property -->
<table class="data-table w3-table-all" border="2px">
<tr class="data-heading"> <!-- initialize table tag -->
<?php while ($property = mysqli_fetch_field($result)) : ?>
<td><?php echo $property->name; ?></td> <!-- get field name for header -->
<?php $all_property[] = $property->name; //save those to array ?>
<?php endwhile; ?>
</tr> <!-- end tr tag -->
<!-- showing all data -->
<?php while ($row = mysqli_fetch_array($result)) : ?>
<tr>
<?php foreach ($all_property as $item) : ?>
<td><?php echo $row[$item]; ?></td> <!-- get items using property value -->
<?php endforeach; ?>
</tr>
<?php endwhile; ?>
</table>
<?php endif; ?>
</div>
</div>
<script>
document.getElementById('select-menu').addEventListener('change', function() {
document.getElementById('form-menu').submit();
});
</script>
</body>
</html>
Handy links:
- Get table names using SELECT statement in MySQL
- Examples of how to do query, style, dom, ajax, event etc like jQuery with plain javascript.
Hope this helps :)

Unable to update MYSQL database table fields using php in XAMPP

So, I am trying to design a php website, and so far it works well in terms of adding an entry to the list table.
The problem is, it isnt able to update the table using edit.php. When the edit link is clicked it shows a message:
"There is no data to be edited."
But if I try to manually put localhost/edit.php**?id=1** it shows the id numbered list and works fine. Please help.
home.php
<html>
<head>
<title>My first PHP Website</title>
</head>
<?php
session_start(); //starts the session
if($_SESSION['user']){ // checks if the user is logged in
}
else{
header("location: index.php"); // redirects if user is not logged in
}
$user = $_SESSION['user']; //assigns user value
?>
<body>
<h2>Home Page</h2>
<hello>!
<!--Display's user name-->
Click here to go logout<br/><br/>
<form action="add.php" method="POST">
Add more to list: <input type="text" name="details" /> <br/>
Public post? <input type="checkbox" name="public[]" value="yes" /> <br/>
<input type="submit" value="Add to list"/>
</form>
<h2 align="center">My list</h2>
<table border="1px" width="100%">
<tr>
<th>Id</th>
<th>Details</th>
<th>Post Time</th>
<th>Edit Time</th>
<th>Edit</th>
<th>Delete</th>
<th>Public Post</th>
</tr>
<?php
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("first_db") or die("Cannot connect to database");
$query = mysql_query("select * from list");
while($row = mysql_fetch_array($query))
{
print "<tr>";
print '<td align="center">'. $row['id'] . "</td>";
print '<td align="center">'. $row['details'] . "</td>";
print '<td align="center">'. $row['date_posted'] . " - " . $row['time_posted'] . "</td>";
print '<td align="center">'. $row['date_edited'] . " - " . $row['time_edited'] . "</td>";
print '<td align="center">edit</td>';
print '<td align="center">delete</td>';
print '<td align="center">'. $row['public'] . "</td>";
print "</tr>";
}
?>
</table>
</body>
</html>
)
edit.php
<html>
<head>
<title>My first PHP website</title>
</head>
<?php
session_start(); //starts the session
if($_SESSION['user']){ //checks if user is logged in
}
else{
header("location:index.php"); // redirects if user is not logged in
}
$user = $_SESSION['user']; //assigns user value
$id_exists = false;
?>
<body>
<h2>Home Page</h2>
<p>Hello <?php Print "$user"?>!</p> <!--Displays user's name-->
Click here to logout<br/><br/>
Return to Home page
<h2 align="center">Currently Selected</h2>
<table border="1px" width="100%">
<tr>
<th>Id</th>
<th>Details</th>
<th>Post Time</th>
<th>Edit Time</th>
<th>Public Post</th>
</tr>
<?php
if(!empty($_GET['id']))
{
$id = $_GET['id'];
$_SESSION['id'] = $id;
$id_exists = true;
mysql_connect("localhost", "root","") or die(mysql_error()); //Connect to server
mysql_select_db("first_db") or die("Cannot connect to database"); //connect to database
$query = mysql_query("Select * from list Where id='$id'"); // SQL Query
$count = mysql_num_rows($query);
if($count > 0)
{
while($row = mysql_fetch_array($query))
{
Print "<tr>";
Print '<td align="center">'. $row['id'] . "</td>";
Print '<td align="center">'. $row['details'] . "</td>";
Print '<td align="center">'. $row['date_posted']. " - ". $row['time_posted']."</td>";
Print '<td align="center">'. $row['date_edited']. " - ". $row['time_edited']. "</td>";
Print '<td align="center">'. $row['public']. "</td>";
Print "</tr>";
}
}
else
{
$id_exists = false;
}
}
?>
</table>
<br/>
<?php
if($id_exists)
{
Print '
<form action="edit.php" method="POST">
Enter new detail: <input type="text" name="details"/><br/>
public post? <input type="checkbox" name="public[]" value="yes"/><br/>
<input type="submit" value="Update List"/>
</form>
';
}
else
{
Print '<h2 align="center">There is no data to be edited.</h2>';
}
?>
</body>
</html>
<?php
if($_SERVER['REQUEST_METHOD'] == "POST")
{
mysql_connect("localhost", "root","") or die(mysql_error()); //Connect to server
mysql_select_db("first_db") or die("Cannot connect to database"); //Connect to database
$details = mysql_real_escape_string($_POST['details']);
$public = "no";
$id = $_SESSION['id'];
$time = strftime("%X");//time
$date = strftime("%B %d, %Y");//date
foreach($_POST['public'] as $list)
{
if($list != null)
{
$public = "yes";
}
}
mysql_query("UPDATE list SET details='$details', public='$public', date_edited='$date', time_edited='$time' WHERE id='$id'") ;
header("location: home.php");
}
?>
and here's the one with ?id=1 in the url
http;//s15,postimg,org/yoabiq0p7/screenshot_21,png (change the commas with fullstops).
You are printing only the edit.php, you need to print the entire edit link.
print '<td align="center">edit</td>';
Replace this line with:
print '<td align="center">edit</td>';
This will solve the problem.
P.S: Be careful, your code is open for SQL Injection! Make sure to use mysql_real_escape_string() in this place:
$id = mysql_real_escape_string($_GET['id']);
If the id is only number, you can do the following too to avoid SQL Injection:
$id = intval($_GET["id"]);
The SQL Injection thing is very serious and you need to filter what comes from outside. I recommend using prepared statement PDO too.
you arent passing the data in the home.php
you are doing normal link to edit.php and you arent passing the data ?id=1
try edit this:
print '<td align="center">edit</td>';
to this:
print '<td align="center">edit</td>';

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.

Categories