Displaying mysql results inside a table using php - 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();
?>

Related

Getting a specific row from PHP database to add to a new empty database upon clicking an "add to playlist button"

I have a group project for my web programming class, we are creating a simple music website and have created a database using phpmyadmin for each genre, we have a add to playlist button that should add the selected song to the empty database but we can not figure out why it is not working.
<div id="navbar">
<table>
<tr>
<td>
<font size="6"><b>Home</font>
</td>
<td>
<font size="6"><b>Pop</font>
</td>
<td>
<font size="6"><b>Hip-Hop</font>
</td>
<td>
<font size="6"><b>Rock</font>
</td>
<td>
<font size="6"><b>Country</font>
</td>
<td>
<font size="6"><b>Alternative</font>
</td>
<td>
<font size="6"><b>My Playlist</font>
</td>
</tr>
</table>
</div>
<!-- End of navbar div -->
<br>
<!-- PHP code here to display the appropriate databse table (genre/playlist) -->
<?php
$dbc = mysqli_connect("localhost", "root", "", "Music Website") or die("Bad Connect:" . mysqli_connect_error());
$sql = "SELECT * FROM AltMusic";
$result = mysqli_query($dbc, $sql) or die("Bad Query: $sql");
echo "<table id = 'database'>";
echo "<tr id = 'tableHead'>
<td class = 'titleCells'>Title</td>
<td class = 'titleCells'>Artist</td>
<td class = 'titleCells'>Album</td>
<td class = 'titleCells'>YouTube</td>
<td class = 'titleCells'>Genre</td>
<td class = 'titleCells'>Add to Playlist</td>
</tr>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>
<td class = 'cells'>{$row['Title']}</td>
<td class = 'cells'>{$row['Artist']}</td>
<td class = 'cells'>{$row['Album']}</td>
<td class = 'cells'><a href='" . $row['YouTube'] . "'target = _blank>" .
$row['YouTube'] . "</a></td>
<td class = 'cells'>{$row['Genre']}</td>
<td id = 'add' class = 'cells'>" ?>
<form action='' method='POST'>
<input type='submit' name='submit' value="+"/>
</form><?
if (isset($_POST['submit'])) {
$sql2 = "INSERT INTO Playlist(`ID`, `Title`, `Artist`, `Album`, `YouTube`,
`Genre`)
SELECT `ID`, `Title`, `Artist`, `Album`, `YouTube`, `Genre`FROM Pop
WHERE ";
}
echo "</td>
</tr>";
}
echo "</table>";
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
echo "<br> Title: " . $row['Title'] . " Artist: " . $row["Artist"] . " Album: " .
$row["Album"] . "YouTube: " . $row["YouTube"] . "Genre: " . $row["Genre"] . "Add to Playlist: " .
$row["Add to Playlist"] . "<br>";
}
} else {
echo "0 results";
}
$dbc->close();
?>
<!-- Bookmark to allow uesrs to return to the top of the page once at the bottom -->
<a href=#top>
<font size="6">Back to top</font>
</a>
I have tried to use isset($_POST("") to add it but it can only figure out how to fetch the entire array instead on one single selection.
Please consider that I, as well as all of the members in my groups are fairly new to web programming. If I have not posted correctly or not given specific enough ideas about what I am trying to do please let me know in a considerate way. Thank you for any help you can provide.

Php remaking a table after data is added to the sql database

I'm trying to display data from my SQL database unto this page. When I run my code with only one data in the SQL database so if there is only one Wifi to fetch then everything looks normal and works well, but as soon as the user adds another wifi then the table is drawn again on top of the other table
A picture with only one wifi in my database
A picture with only two wifi in my database
Here is my wifi_page.php:
<?php
require_once 'header.php';
require_once 'connect.php';
$sql = "SELECT ID, Name, Password FROM wifi";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$newWifi = "wifi_register_page.php";
echo"
<table>
<tr>
<td>Name</td>
<td>Password</td>
<td>+
</td></tr>
<tr>
<td> ". $row["Name"]. "</td>
<td>". $row["Password"]. "</td>
<td></td>
</tr>
</table>";
}
} else {
echo "0 results";
}
$mysqli->close();
require_once 'footer.php'
?>
If you need any more code or images just let me know in the comments. Thank you in advance!
You need to take the table and the header out of the while, otherwise it will create a new table for each row of your database.
<?php
require_once 'header.php';
require_once 'connect.php';
$sql = "SELECT ID, Name, Password FROM wifi";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
$newWifi = "wifi_register_page.php";
echo "
<table>
<tr>
<td>Name</td>
<td>Password</td>
<td>+
</td>
</tr>
";
// output data of each row
while($row = $result->fetch_assoc()) {
echo"
<tr>
<td> ". $row["Name"]. "</td>
<td>". $row["Password"]. "</td>
<td></td>
</tr>
";
}
echo '</table>';
} else {
echo "0 results";
}
$mysqli->close();
require_once 'footer.php'
?>

Populate table based on selected dropdown value

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>

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.

Want to make each tuple point to a different link, how do i do it?

Basically, I want to make each tuple point to different URL so that I can view the semesters of the clicked department, and I am viewing this in a table.
I tried passing an href tag before echo in this code, but that is taking me to the same link when I press any tuple in the table.
<!Doctype html>
<table border="1" id="table">
<p>
<tr>
<th bgcolor="#9999FF">Departements</th>
</>
</tr>
<?php $servername="localhost" ; $username="root" ; $password="" ; $dbname="dbms_pro" ; // Create connection $conn=n ew mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT dep_name FROM department"; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { echo "
<tr>
<td department:>" . $row["dep_name"]. "</tr>
</td>"; } } else { echo "0 results"; } $conn->close(); ?>
</table>
</html>
There is basically one tag in html to make hyperlinks and it is a (http://www.w3schools.com/tags/tag_a.asp):
You need to iterate over array and add a unique id to href attribute to make what you want. Example code below, however it's not good to mix html and php in one file.
<!Doctype html>
<head></head>
<body>
<table border="1" id="table">
<p>
<tr>
<th bgcolor="#9999FF">Departements</th>
</>
</tr>
<?php foreach ($departements as $row) {
echo "
<tr>
<td><a href='/department/{$row["id"]}'>{$row["dep_name"]}</tr>
</td>";
}
?>
</table>
</body>
</html>

Categories