I have a table in a database with some values referring to humidity, temperature, brightness and noise of a specific room in a specific hour (in a specific date). I want to put them on a html table like this:
example html table
The problem is that my html table has to display only the values of a precise day, so at the end of the day the html table has to have 96 values (from 00:00 to 23:45) and in the next day it has to be emptied.
I realized that there might be two ways to solve it:
At the end of the day, the rows must be deleted, so with the two loops
(one to create the rows and the other for the single cells), the table for the next day can be re-created. I don't know how to delete the html rows!!
At the end of the day, with a "pointer" it is possible to return to
the first row and to change cell's contents.
In both cases, I need a "pointer" that allows to return in the beginning of the table.
Here is my code but there are some bugs. Please also let me know if you have different ideas.
<?php
// Ignore user aborts and allow the script
// to run forever
ignore_user_abort(true);
?>
<html>
<head>
<meta charset="utf-8">
<script>
function waiting()
{
//wait 15 minutes (900 seconds) until the insertion of new data
setTimeout(function() {alert("New line added!"); }, 900);
}
</script>
<title> Benvenuto </title>
</head>
<body>
<table style="width:100%" border='0'>
<tr>
<td valign="top">
<input type="date" value="<?php echo date("Y-m-d");?>">
</td>
</tr>
</table>
<table border='0' style="width:100%">
<tr>
<td>
<b> Hour </b>
</td>
<td>
<b> ID room </b>
</td>
<td>
<b> Humidity </b>
</td>
<td>
<b> Temperature </b>
</td>
<td>
<b> Brightness </b>
</td>
<td>
<b> Noise </b>
</td>
</tr>
</table>
<?php
mysql_connect(" localhost", "root", "root");
mysql_select_db("my_db");
$date = date("d/m/Y");
$hour_now = date('H:i', strtotime('00:00'));
$hour_end = date('H:i', strtotime('23:45'));
$row = 96; //Dynamic number for rows
$col = 6; // Dynamic number for columns
do
{
echo "<table>";
//rows loop
for($i=0;$i<$row;$i++)
{
echo "<tr>";
//cells loop
for($j=0;$j<$col;$j++)
{
echo "<td>";
//hour
$hour_on_table = mysql_query("SELECT hour FROM DATA WHERE hour='$hour_now' AND date='$date'");
echo mysql_result($hour_on_table, 0);
echo "</td>";
echo "<td>";
//id_room
$id_room = mysql_query("SELECT id_room FROM DATA WHERE hour='$hour_now' AND date='$date'");
echo mysql_result($id_room, 0);
echo "</td>";
echo "<td>";
//humidity
$humidity = mysql_query("SELECT humidity FROM DATA WHERE hour='$hour_now' AND date='$date'");
echo mysql_result($humidity, 0);
echo "</td>";
echo "<td>";
//temperature
$temperature = mysql_query("SELECT temperature FROM DATA WHERE hour='$hour_now' AND date='$date'");
echo mysql_result($temperature, 0);
echo "</td>";
echo "<td>";
//brightness
$brightness = mysql_query("SELECT brightness FROM DATA WHERE hour='$hour_now' AND date='$date'");
echo mysql_result($brightness, 0);
echo "</td>";
echo "<td>";
//noise
$noise = mysql_query("SELECT noise FROM DATA WHERE hour='$hour_now' AND date='$date'");
echo mysql_result($noise, 0);
echo "</td>";
echo '<script type="text/javascript"> attesa(); </script>';
$hour_now = date('H:i', strtotime($hour_now) +900); //add 15 min
}
echo "</tr>";
}
echo "<table>";
}
?>
</body>
</html>
I think your best solution would be to write a better query that selects all fields of all records for a day. And then just iterate through the results and echo it.
<?php
if($_REQUEST['date'])
$date = new DateTime($_REQUEST['date']);
else
$date = new DateTime("now");
$db = mysqli_connect('localhost', 'root', 'root', 'my_db');
// Check for SQL connection errors here
$records = mysqli_query($db, "SELECT * FROM DATA WHERE `date`='".$date->format('m/d/Y')."' ORDER BY `hour`");
?>
<html>
<head>
</head>
<body>
<form>
<input type='date' name='date' value='<?php echo $date->format('m/d/Y'); ?>' />
<button type='submit'>Update</button>
</form>
<table>
<thead><tr>
<td>Hour</td>
<td>ID Room</td>
<td>Humidity</td>
<td>Temperature</td>
<td>Brightness<td>
<td>Noise<td>
</tr></head>
<tbody>
<?php
while($record = mysqli_fetch_assoc($records)){
echo "<tr>";
echo "<td>{$record['hour']}</td>";
echo "<td>{$record['ID_room']}</td>";
echo "<td>{$record['humidity']}</td>";
echo "<td>{$record['temperature']}</td>";
echo "<td>{$record['brightness']}</td>";
echo "<td>{$record['noise']}</td>";
echo "</td>";
}
?>
</tbody>
</table>
</body>
</html>
No. You sent it out to the browser. You have to use javascript to delete it.
But you should probably not make your php script run forever. Something will time out sooner or later between your server and your browser.
You should use an ajax call in setTimeout to refresh the data. E.g. you could use jquery.Ajax, parse the response with jQuery.parseHTML, cut out the table from it, and replace the old table with replaceWith
Something like this (untested):
$.ajax(url).done(function(data) {
$('table:first') // this finds the first table element in the html
.replaceWith(
$.parseHTML(response).find('table:first') // cut out the table element from the response
); // replace the table in the html with the one in the ajax response
})
Related
I have trouble to use for loop's variable $counter with
$HA_Row = mysql_fetch_array($HA_Res);
to indicate which row's data I am going to get. Basically, I have no idea to use $counter and $HA_Res together.
I want to it can display different rows' data of my database.
For example, like
echo "$HA_Row[Check_In_Date]"
I have tried
echo "$HA_Row[$counter][Check_In_Date]"
and
echo "$HA_Row[Check_In_Date][$counter]", echo "[$counter]$HA_Row[Check_In_Date]"
but none of them works.
Thank you so much! Appreciate your time.
<?php
session_start();
include_once 'dbconnect.php';
if(!isset($_SESSION['Hotel_User_ID']))
{
header("Location: index.php");
}
$res = mysql_query("SELECT * FROM Hotel_Info WHERE Hotel_ID =".$_SESSION['Hotel_User_ID']);
$userRow = mysql_fetch_array($res);
$HA_Res = mysql_query("SELECT * FROM Hotel_Account WHERE Hotel_ID =".$_SESSION['Hotel_User_ID']);
$HA_Row = mysql_fetch_array($HA_Res);
$HA_Count = mysql_num_rows($HA_Res);
// echo "$HA_Count". "<br>";
// echo "$HA_Row[Check_In_Date]";
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Hello - <?php echo $userRow['Hotel_Email']; ?></title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="header">
<div id="left">
<label>Welcome <?php echo $userRow['Hotel_Uname']; ?> </label>
</div>
<div id="right">
<div id="content">
Sign Out
</div>
</div>
</div>
<div id="menu">
Manage <br>
Update
</div>
<div id="body">
<center>
<div id="Hotel-InfoForm">
<form method="post" enctype="multipart/form-data">
<!-- <table.ver2 align="center" width="60%" border="0"> -->
<table align="center" width="85%" border = "1">
<tr>
<th>Check In Data</th>
<th>Check Out Data</th>
<th>Theme</th>
<th>Bed Size</th>
<th>First Name</th>
<th>Last Name</th>
<th>Gender</th>
<th>Age</th>
<th>Phone Number</th>
<th>Email</th>
</tr>
<?php
for($counter = 0; $counter < $HA_Count; $counter = $counter + 1)
{
// using $counter for $HA_Row[....]
echo "<tr>";
echo "<td>";
echo "$HA_Row[Check_In_Date]";
echo "</td>";
echo "<td>";
echo "$HA_Row[Check_Out_Date]";
echo "</td>";
$Theme_Res = mysql_query("SELECT * FROM Theme WHERE Theme_ID = ".$HA_Row[Theme_ID]);
$Theme_Row = mysql_fetch_array($Theme_Res);
echo "<td>";
echo "$Theme_Row[Theme_Name]";
echo "</td>";
echo "<td>";
echo "$Theme_Row[Bed_Size]";
echo "</td>";
$Guest_Res = mysql_query("SELECT * FROM Guest_Info WHERE Guest_ID = ".$HA_Row[Guest_ID]);
$Guest_Row = mysql_fetch_array($Guest_Res);
echo "<td>";
echo "$Guest_Row[First_Name]";
echo "</td>";
echo "<td>";
echo "$Guest_Row[Last_Name]";
echo "</td>";
echo "<td>";
echo "$Guest_Row[Gender]";
echo "</td>";
function ageCalculator($dob)
{
if(!empty($dob))
{
$birthdate = new DateTime($dob);
$today = new DateTime('today');
$age = $birthdate->diff($today)->y;
return $age;
}
else
{
return 0;
}
}
echo "<td>";
echo ageCalculator($Guest_Row[Birth_Day]);
echo "</td>";
echo "<td>";
echo "$Guest_Row[Phone_Num]";
echo "</td>";
echo "<td>";
echo "$Guest_Row[Email]";
echo "</td>";
echo "</tr>\n";
}
?>
</table>
</form>
</div>
</center>
</div>
</body>
</html>
You could use mysql_fetch_assoc and while looping, like this:
while($HA_Row = mysql_fetch_assoc($HA_Res)){
echo $HA_Row[Check_In_Date]."<br>";
};
This while will loop in each instance!
You don't normally use a counter to control fetch, especially if you just want to process the records in sequence. Each call to fetch will return the next row in the result set without further action on your part.
First, replace all your mysql_* calls with their mysqli_* counterparts. Then replace your line
for($counter = 0; $counter < $HA_Count; $counter = $counter + 1)
with
while ($HA_Row = mysqli_fetch_array($HA_Res))
On each loop, mysqli_fetch_array returns the next row, and after reading the last row the next call returns false, which exits the loop.
Switching to mysqli_* or PDO will also gain you prepared statements, which help to protect against SQL injection, among numerous other benefits.
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.
I have the following code:
$sql = "SELECT * FROM Tickets WHERE stat='Open'";
$result = mysql_query($sql);
mysql_close($con);
?>
<!DOCTYPE>
<html>
<body>
<table class="striped">
<tr class="header">
<td>Username</td>
<td>Title</td>
<td>Description</td>
<td>Admin Name</td>
<td>Category</td>
<td>Status</td>
<td>Urgency</td>
<td>Time In</td>
<td> </td>
</tr>
<?php
while ($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>".$row[username]."</td>";
echo "<td>".$row[title]."</td>";
echo "<td>".$row[description]."</td>";?>
<td><select>
<?php
echo "<option value'".$row[admin_name]."'>".$row[admin_name]."</option>";
$sql = mysql_query("SELECT username FROM Users WHERE user_type='admin'");
while ($u = mysql_fetch_array($sql)){
echo "<option value='".$u['username']."'>".$u['username']."</option>";
}
?>
</select></td>
<?php
echo "<td>".$row[category]."</td>";
echo "<td>".$row[stat]."</td>";
echo "<td>".$row[urgency]."</td>";
echo "<td>".$row[time_in]."</td>";
echo "<td><a href='close.php'>Close Ticket</a></td>";
echo "</tr>";
}
?>
</table>
<a href='update.php'>Update</a>
</body>
</html>
I have two links on this page. Both of them need to update a SQL database. The Close ticket link needs to just update the single row, while the update link should update all of them. I am not sure how to get the info from one php to the next. It seems like you can put the individual row information into a Post array for the close ticket link, but I am not sure how. For the update link it needs to take the value of the dropdown in the table and change the admin_name field to that value.
Insert Is Fine But if I select this value from database All Values are fine but single values fetch array problem I don't know how to solve this task. Please Update this code asap.
This Is Insert Code .....
<?php
if(isset($_POST['sendmessage'])){
$entermessage = $_POST['teachermessage'];
$checkbox_user = $_POST['usernameallcheckbx'];
$arr = implode(',',$checkbox_user);
//$arr2 = explode(',',$arr);
$insert = mysql_query("INSERT into usermessages(fromteacher,toparent,messages) VALUES('".$_SESSION['username']."','$arr','$entermessage')");
if($insert == 1){
echo "<h1>successful</h1>";
}
else{
echo mysql_error();
}
}
?>
<form method="post">
<div style="float:left; width:450px;"><br/><br/>Message: <br/>
<textarea style="width:400px; height:300px;" name="teachermessage"></textarea><br/>
<input type="submit" value="Send" name="sendmessage" /></div>
<div style="float:left; with:200px; padding-top:55px;">
<table>
<tr>
<?php
$select_query1 = mysql_query("SELECT * FROM register_user WHERE teacher='$teachername'");
while($chckbx=mysql_fetch_array($select_query1))
{
?>
<td><?php echo "<input type='checkbox' name='usernameallcheckbx[]' value=". $chckbx['userid']." />"; ?></td>
</tr>
<tr>
<td><?php echo $chckbx['parent_fname']." ".$chckbx['parent_lname']; ?></td>
</tr>
<?php
}
?>
</table>
</div>
</form>
And This Is Select Code....
<h2>Messages</h2>
<?php
$select_query3 = mysql_query("SELECT * FROM usermessages");
$fetch= mysql_fetch_array($select_query3);
$data=$fetch['toparent'];
$arr=explode(',',$data);
//$userids=explode(',',$data);
$sessionshow=$_SESSION['userid'];
$userids=in_array("$sessionshow",$arr);
$select_query2 = mysql_query("SELECT * FROM usermessages WHERE toparent in ('$userids')='".$_SESSION['userid']."'");
?>
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<th>Teacher Name</th>
<th>Message</th>
</tr>
<?php
while($fetch_name2=mysql_fetch_array($select_query2))
{
echo "<tr>";
echo "<td>".$fetch_data=$fetch_name2['fromteacher']."</td>";
echo "<td>".$fetch_data=$fetch_name2['messages']."</td>";
echo "</tr>";
}
?>
</table>
I have only put this as an answer to show some incorrect code - remove fetch data from your loop as it doesn't do anything
while($fetch_name2=mysql_fetch_array($select_query2))
{
echo "<tr>";
echo "<td>".$fetch_name2['fromteacher']."</td>";
echo "<td>".$fetch_name2['messages']."</td>";
echo "</tr>";
}
even better is use of a HEREDOC:
while($fetch_name2=mysql_fetch_array($select_query2))
{
echo <<<EOF
<tr>
<td>{$fetch_name2['fromteacher']}</td>
<td>{$fetch_name2['messages']}</td>
</tr>
EOF;
}
I really can't figure out what you're trying to do, but maybe this is the query you want:
SELECT * FROM usermessages WHERE FIND_IN_SET('$sessionshow', toparent)
FIND_IN_SET(str, strlist) searches the comma-separated list in strlist for an element that equals str, and returns the position in the list; if it's not found it returns 0, which counts as false.
I can't see any purpose to any of the code that uses $select_query3.
I am making a game for class and I have a leaderboards page. What I am wanting to do is dynamically add a new row to the table every time a new result is added to the database.
This is my PHP SELECT *:
<?php $records = array();
if ($results = $db->query("SELECT * FROM user_settings, leaderboards")) {
if ($results->num_rows) {
while ($row = $results->fetch_object()) {
$records[] = $row;
}
$results->free();
}
}
?>
<?php foreach ($records as $data) { ?>
...
My table looks like this:
<table class="leaderboard">
<tr>
<th>ID</th><th>First Name</th><th>Last Name</th><th>Robot Name</th><th>Power Remaining</th><th>Level</th>
</tr>
<tr>
<td><?php echo escape($data->id); ?></td><td><?php echo escape(htmlentities($data->first_name)); ?></td><td><?php echo escape(htmlentities($data->last_name)); ?></td><td><?php echo escape(htmlentities($data->robot_name)); ?></td><td><?php echo escape($data->power_remaining); ?></td><td><?php echo escape($data->level) ?></td>
</tr>
<tr>
</tr>
</table>
This successfully grabs the value from the database however how can I dynamically add a new record to the HTML table every time a new value is entered into the database?
Make the <td> in the foreach with a simple echo in PHP, its should work.
For example:
<?php foreach ($records as $data) {
echo "<td> escape($data->id) ... </td>"
} ?>
You need to check current result count with Ajax every some time period, for ex. every minute. If there is more results - send them to client side and add them to table with javascript.