From the looped data I'd like to auto refresh only the data retrieved from the database, and not the whole layout. Currently I re-loop the complete layout but that seems somewhat clumsy (this table is a simplified example). Some direction or advice is appreciated!
<?
//.. rawdata.php ..//
while($row = mysql_fetch_array($result)) {
//building table by looping
?>
<tr>
<td><? echo $row['uniqueid']; ?></td>
<td><? echo $row['firstname']; ?></td>
<td><? echo $row['surname']; ?></td>
</tr>
<?
}
?>
<!-- index.php -->
<script type="text/javascript">
var auto_refresh = setInterval(function() {
$('#loadRawData').load('rawdata.php');
}, 5000);
</script>
<!--...-->
<div id="loadRawData"></div>
If you only update or add records, you could add a “version” column to your table. Each time you update a row, or insert a new row, you increment the version and add it to the row.
You transmit the version to the client (it's a MAX on the version column). When the client does its “refresh” request, it sends you the version it had last downloaded, and you simply send the rows that verify a condition such as WHERE version > clientVersion.
It will be trickier if rows may be deleted, because in that case you will need to keep track of deleted rows in the table, in order to forward the “delete” operations to the clients. But you can manage them with the same “version” mechanism.
Related
This is the HTML/PHP , I am using to display some data.
<body>
<section>
<h1>Facebook Search</h1>
<!-- TABLE CONSTRUCTION-->
<table>
<tr>
<th>Comment</th>
<th>Comment Made By</th>
<th>Commentor's Profile Link</th>
<th>Comment ID</th>
<th>Post ID</th>
</tr>
<!-- PHP CODE TO FETCH DATA FROM ROWS-->
<?php // LOOP TILL END OF DATA
while($rows=$result->fetch_assoc())
{
?>
<tr>
<!--FETCHING DATA FROM EACH
ROW OF EVERY COLUMN-->
<td><?php echo $rows['comtext'];?></td>
<td><?php echo $rows['comby'];?></td>
<td><?php echo $rows['compro'];?></td>
<td><?php echo $rows['commentid'];?></td>
<td><?php echo $rows['postid'];?></td>
</tr>
<?php
}
?>
</table>
</section>
</body>
</html>
and I am getting the data like this from the db.
$sql = "SELECT comments.*, posts.postid FROM comments JOIN posts USING(postid)";
$result = $mysqli->query($sql);
$mysqli->close();
This outputs a single table with all the data. My question is , is there a way to break the single table into tables when the value of postid changes? It goes like..is 1 for x number of rows, then 2 for x number of rows and so on. I wanted to have a little break between those tables.
is there a way to break the single table into tables when the value of postid changes
You should stop using "SELECT *", it's inefficient and makes code difficult to maintain. While we're talking about style here, you swap back and forth between PHP and inline HTML which also impacts the readability of your code.
As to your question...
You need to ensure that the output of your query is sorted by postid - or you're going to get a lot of tables.
Use a state variable to track the postid from the previous iteration of the loop.
$prev=0;
while($rows=$result->fetch_assoc()) {
if ($rows['postid']!=$prev) {
close_table();
open_table();
$prev=$rows['postid'];
}
output_row($rows);
}
close_table();
The problem with this is that each iteration of the expects that you've already written <table> to the output stream - including the first iteration. You could do this before the loop - but you'll end up with an empty table at the top of the page. You could add another state variable to track whether you have opened a table tag yet. Personally, I'd go with making inferences from the value of the existing state variable:
$prev=0;
while($rows=$result->fetch_assoc()) {
if ($rows['postid']!=$prev) {
$prev || close_table();
open_table();
$prev=$rows['postid'];
}
output_row($rows);
}
close_table();
(the || is a quick way of writing if (not(condition)) do something() )
Note that unless you fix the size of the columns, then each table will be independently sized to fit the data that resides within it.
Im making a forum and in one of the pages i show the topics i have with an id i got from the page before, and in that page i also want to show how many visits the topics have, as such i call the id of the topic, put it in a function that i call to when i click on a link with onclick, so that once somebody clicks on it to access it, it also updates the visits count on the database. Point is, it doesnt work.
PHP CALL
<?php
include("db.php");
$sql="SELECT `id`, `nombre`, `creador`, `dept_no`, `fechac`, `visitas` FROM `temas` WHERE `dept_no`=".(desencryptar($_GET["id"]));
if($resultado = $mysqli->query($sql)) {
if($resultado->num_rows>0){
while($fila = $resultado->fetch_assoc()) {
$id=$fila["id"];
$nombre=$fila["nombre"];
$creador=$fila["creador"];
$dept_no=$fila["dept_no"];
$fechac=$fila["fechac"];
$visitas=$fila["visitas"]; ?>
After which i call it when showing it.
HTML
<tr>
<td>
<a onclick="visitas(<?php echo $id;?>)" id="tema" href="posts.php?id=<?php echo encryptar($id);?>" target="_self"><?php echo $nombre;?></a>
<div style="padding-top:5px">
<span>Por <?php echo $creador;?>, <?php echo $fechac;?></span>
</div>
</td>
<td style="text-align: center;"><?php echo Contar($id);?></td>
<td style="text-align: center;"><?php echo $visitas;?></td>
<td>Por <?php echo $creador;?><br><span>En </span><?php echo $fechac;?></td>
PHP FUNCTION i created on a functions.php
function visitas($valor) {
include("db.php");
$sql2="UPDATE `temas` SET `visitas` = `visitas` + 1 WHERE `id`=".$valor; }
you are using a Javascript Function visitas() and created a PHP function visitas ?
Know that Javascript function can't execute PHP function...
You need to create a Javascript function that will execute a Ajax request to a php file that contain your Php function, then redirect the user after success response.
Example:
jQuery Ajax POST example with PHP
I have an array of items kept in session cart. It gets populated in a table. each row has an index and a button to remove this particular item(items array) from $_SESSION['cart']..
This is the code I have at the moment:
$i = 0;
foreach($_SESSION['cart'] as $item)
{
//Populate items in a table ?>
<tr>
<td><center><?php echo $i; ?></center></td>
<td><center><?php echo $item['item'];?></center></td>
<td><center><?php echo '£'. $item['unitprice'];?></center></td>
<td><center><?php echo $item['quantity'];?></center></td>
<td><center><?php echo '£'.($item['unitprice'] * $item['quantity']) ?></center></td>
<td><input type="submit" value="Remove" Onclick = unset($_SESSION['cart'][$i]); ></td>
</tr>
<?php
$total += ($item['unitprice'] * $item['quantity']);
$i++;
}
All I want to do is to remove one single row of data (each row contains index, item, item price, total(if there are more than one item) and remove button) from session cart. Thanks in advance..
The unset is correct, but PHP is executed on the servers side. So because this is a client action, you'll need to use JavaScript to pick up the action. (you could also use an old fasion form as well). I prefer to use jQuery since it allready has the built in ajax support and makes it easy. Basically, just call a function from the onClick that passes the "ID" of the element you want to delete. Then that function will make an AJAX call to another script that will take that ID and remove the element. When that script returns a success, have JavaScript delete (or hide) the element. This way the user never leaves or refreshes the page, and the script can do some extra cleanup (like database updates, session updates, validate request, etc.)
i = 0;
foreach($_SESSION['cart'] as $item)
{
//Populate items in a table ?>
<tr>
<td><center><?php echo $i; ?></center></td>
<td><center><?php echo $item['item'];?></center></td>
<td><center><?php echo '£'. $item['unitprice'];?></center></td>
<td><center><?php echo $item['quantity'];?></center></td>
<td><center><?php echo '£'.($item['unitprice'] * $item['quantity']) ?></center></td>
<td><input type="submit" value="Remove" onClick="RemoveItem(<?= $i ?>)" ></td>
</tr>
<?php
$total += ($item['unitprice'] * $item['quantity']);
$i++;
}
Here I've changed the onClick section to use a javascript call instead. You'll notice I used the <?= tag instead of a full <?php echo. This is because as of php5 you can use the shorthand <?= to echo an expression.
In your script section you can do something like this. I use POST since it's more secure.
function RemoveItem(id) {
$.post('script-to-remove.php',
{ ItemID: id },
function(data) {
if(data==='success') {
//Remove item from DOM
} else alert("There was an error!"); //If you want error handling
}
);
}
For removing items from the dom, its a bit trickier with tables since none of the cool effects will really work, such as fadeOut, slideUp, animate, etc. I would look into reformatting it with divs.
As for the php script it calls, its as simple as calling the unset. You can develop it more, so as to possibly check the validity of the request, but for now, I'm just going to do the unset.
<?php
$ItemID = isset($_POST['ItemID'])?intval($_POST['ItemID']):-1;
if($ItemID<0) die("Invalid ID"); //Change this if you want
if(isset($_SESSION['cart'][$ItemID])) unset($_SESSION['cart'][$ItemID]);
echo 'success';
?>
Basically in this, I first check that the right parameter came in, make sure it's an integer and save it, otherwise I default it to -1. Then if the Item ID is under 0 (so definatly wrong) I tell the script to output the message and quit. Finally I check that there is a value for that ID or index as it really is, and unset it. If it makes it to the end, output the success.
I have wore below code and its working.But I want row number when a ROW clicked(Hope Ajax is okay) and pass it to a php code in same page. I tried javascript it worked,bt not in the way I want. If its in Ajax its better. Any HELP would b gratefull :)
if(isset($_POST['search'])){
$search=mysqli_query($con,"SELECT * FROM bus_fares WHERE route_no='$_POST[route_no]'");
$num_rows = mysqli_num_rows($search);
$search1=mysqli_query($con,"SELECT fare FROM fare limit $num_rows ");
$x = 0;
echo" <table id='my_table'><tr><th>Fare Stage</th>
<th>Location</th>
<th>Fare</th>
</tr>";
while($row=mysqli_fetch_assoc($search) and $row1=mysqli_fetch_assoc($search1)){
echo"<tr>";
echo"<td>".$x."</td>";
echo"<td>".$row['location']."</td>";
echo"<td>".$row1['fare']."</td>";
echo"</tr>";
$x++;
}
echo"</table>";
}
What you really want is to not only store the visual data in your table but also some sort of meta data. There are several ways to achieve this.
Method #1: (ab)use the id or class attributes:
The resulting HTML would look like this:
<!-- example with the id-attribute: -->
<tr id="mysql_row_1"> ... </tr>
<tr id="mysql_row_2"> ... </tr>
<!-- example with the class-attribute: -->
<tr class="mysql_row_1"> ... </tr>
<tr class="mysql_row_2"> ... </tr>
This would both generate valid HTML but you would abuse attribute-tags for a purpose they're not implemented for, what is generally regarded as bad. Imagine if you had to store more than just one value. You could assign multiple classes, but you'd get stuck with the id-tag then. Therefore: don't do this!
You'd have to change your code like this to achieve this solution:
(I assume you want the value of $x as the rownumber.)
while ($row=mysqli_fetch_assoc($search) and $row1=mysqli_fetch_assoc($search1)) {
echo '<tr class="mysql_row_'.$x.'" onclick="getRowNumber()">';
echo "<td>".$x."</td>";
echo "<td>".$row['location']."</td>";
echo "<td>".$row1['fare']."</td>";
echo "</tr>";
$x++;
}
The javascript part:
function getRowNumber() {
var rowNumber = this.className.replace("mysql_row_",""); // fetches the classname and removes the extra-strings
alert(rowNumber); // alerts "1", "2", ...
}
Method #2: Use the data-* attributes:
This solution is valid for HTML5. Please add additional information regarding compatibility if you have some.
Your HTML Code will look like this:
<tr data-mysql_row_number="1" onclick="getRowNumber()"> .... </tr>
<tr data-mysql_row_number="2" onclick="getRowNumber()"> .... </tr>
And the modified javascript:
function getRowNumber() {
alert(this.getAttribute("data-mysql_row_number")); // alerts "1", "2", ...
}
This also generates perfectly valid HTML(5) code and lets you store infinite endless amounts of information since you can specify as many data-* attributes as you want to.
Method #3: use invisible <input> fields:
The resulting HTML code:
<tr onclick="getRowNumber()">
<td>
Normal content of this field
<input type="hidden" name="mysql_row_number" value="1"/>
</td>
</tr>
And the JS code to fetch the values:
function getRowNumber() {
var rowNumber = this.getElementsByName('mysql_row_number')[0].value;
alert(rowNumber); // alerts "1", "2", ...
}
This as well produces valid HTML but is semantically not really correct in my opinion, since the data inside the <input> fields is some kind of loose and not directly connected to the row. Plus you can make multiple <input> fields with the same name.
I would suggest method #2 ( data-* ), as this is the most flexible solution and uses an attribute that has been designed to store meta-data.
Method #1 would work the most reliable across all (older) browsers since all of them support acces to the id or class attribute via JS, as long as you keep the id tag unique.
Method #3 will also be quite reliable with older browsers.
Instead of echo"<tr>"; do :
echo "<tr id='row_".$row['id']."'>";
then when a tr is clicked, just retrieve $(this)[0].id like that with jQuery inside a script tag (be sure jQuery is included, it's a powerful JS library, google it for additional informations) :
<script>
$("#my_table").on("click", "tr", function(){
alert($(this)[0].id.replace("row_", ""));
});
</script>
I have put up some code to make an ajax, php, mysql chat in real time...
this is my code:
-jQuery/Ajax
$(function(){
setInterval(function() {
$('#chMsgCont').load('./ajax/msg.php');
var div = $('#chMsgCont');
var o = div.offset().top;
div.scrollTop( o + 12302012 );
}
,1000);
});
"./ajax/msg.php"
<?php
include("../system/config.site.php");
$query = mysql_query("SELECT * FROM chat_msg ORDER BY timestamp ASC");
while($p = mysql_fetch_assoc($query)) {
$auth = mysql_fetch_assoc(mysql_query("SELECT * FROM chat_users WHERE id = '".$p['auth_id']."'"));
?>
<div class="chatMsg">
<p id="chatPMsg">
<span class="chatTime"><?php echo date("H:i", $p['timestamp']); ?></span>
<b><?php echo $auth['name']." ".$auth['surname']; ?></b><br />
<?php echo stripslashes($p['msg']); ?>
</p>
<p id="chatImg">
<img src="./images/thumb<?php echo $p['auth_id']; ?>.png" />
</p>
<div style="clear:both;"><!– –> </div>
</div>
<?php
}
?>
I haven't found any method for not loading every second the "msg.php" file... I thought: is it possible to load initially the messages and then with setIntervall check for new messages to append to #chMsgCont? I think it is possible, but i can't figure out how to code it :/, can anyone help me?
Yes it is possible to load all messages upon initial page load; then subsequently update the chat window with new messages (have you ever wondered how Gmail auto populates new mail into your Inbox without a page refresh? Lots of AJAX requests).
You're on the right track. Just make sure you have a column in your MySQL database that holds a "yes/no" value on whether its a new message or not. Then everytime a new message is fetched using ajax/msg.php, in addition to fetching and outputting the content, perform a SQL update to update the fetched data as well.
Once you have that working you can further optimize your chat application by creating a simplier MySQL SELECT statement that simply checks the count of "new" rows (SELECT COUNT(new_message) FROM messages). Then check the value returned and whether it's greater than 0 before attempting to append content. I would also check for empty return data in your JavaScript to prevent from unnecessarily manipulating DOM elements.