What I have is a PHP code that generates a html table from mysql database, and then I'm trying to use a jQuery addon that makes the table sortable. I've had this problem many times and can't seem to find a solution anywhere... why doesn't jQuery (or is it Javascript period?) work on a PHP output? Isn't there a way around this?
Here's the code:
<html><head>
<title>MySQL Table Viewer</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="http://tablesorter.com/jquery.tablesorter.min.js"></script>
<script src="http://tablesorter.com/addons/pager/jquery.tablesorter.pager.js"></script>
<script>
$(document).ready(function()
{
$("#mytable").tablesorter();
}
);
</script>
</head><body>
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pwd = 'lptm42b';
$database = 'sphinx';
$table = 'spheres';
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
// sending query
$result = mysql_query("SELECT * FROM {$table}");
if (!$result) {
die("Query to show fields from table failed");
}
$fields_num = mysql_num_fields($result);
echo "<h1>Table: {$table}</h1>";
echo "<table id=\"mytable\" border='1'><tr>";
// printing table headers
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
echo "<td>{$field->name}</td>";
}
echo "</tr>\n";
// printing table rows
while($row = mysql_fetch_row($result))
{
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
}
mysql_free_result($result);
?></table>
</body>
</html>
Output is:
<html><head>
<script src="../js/jquery_plugin.tablesorter.min.js"></script>
<script src="../js/jquery-1.6.min.js"></script>
<script src="../js/jquery_plugin.tablesorter.pager.js"></script>
<title>MySQL Table Viewer</title></head><body>
<h1>Table: lobby</h1><table id="mytable" border='1'><thead><tr><td>tableid</td> <td>name</td><td>datecreated</td><td>active</td></tr></thead>
<tbody><tr><td>12341231241</td><td>Oyunum1</td><td>2011-05-09 14:26:51</td><td>0</td> </tr>
<tr><td>6677768</td><td>m2</td><td>2011-05-05 14:26:39</td><td>1</td></tr>
<tr><td>ddf1</td><td>m3</td><td>2011-05-09 14:27:19</td><td>0</td></tr>
<tr><td>7856844444</td><td>m4</td><td>2011-05-09 14:27:31</td><td>0</td></tr>
<tr><td>xxxxde4rfd</td><td>m5</td><td>2011-05-09 14:27:43</td><td>0</td></tr>
</tbody></table>
</body></html>
<script>
$(document).ready(function()
{
$("#mytable").tablesorter();
}
);
</script>
UPDATE: For some reason syntax coloring is lost at the end / script> tag in chrome view source
tablesorter plugin requires THEAD and TBODY tags in table for it to work
You don't gave a #mytable element.
You need to use a selector that matches an element that actually exists.
EDIT: Your PHP has mis-nested quotes, so the ID isn't actually in the string.
Look at the page source.
you should add the ID for the table with "mytable" .
Also alsways put thead, tbody in table tags for better output while using JQuery.
Late coming to this party, but you need to know that document.ready won't pick up dynamically generated html if that html is generated AFTER the dom is loaded initially. There are jQuery plugins to work around this (liveQuery is one of them), but the Document.Ready event fires once per page load, and if the PHP that generates the html is fired AFTER that, then the tablesorter method you call has nothing to sort.
Javascript is a client-side technology, meaning to get it work with elements generated directly by the server through php, there are some gymnastics involved.
Try to read up on the json_encode() function in PHP and ajax calls in general.
Also, you might be interested in the .delegate() jQuery method.
Related
I've searched hard to find a way to print the query of the code above into a HTML part, but i don't find anything. I saw that is possible to present the result by a HTML table using the fetch_assoc() of php. Below is the code, and on a global view the code is fine, because i test it on a full php page. But i need a solution to put it in HTML. Am i trying an impossible thing?
<?php
require_once('connconf.php');
$conn = mysqli_connect($server, $user, $pw, $bdname) or die ('Connection Error');
$sqlquery = "select ID_Vote from Votes where ID_Player = '1'";
if($result = mysqli_query($conn, $sqlquery)) {
$rowcount = mysqli_num_rows($result);
echo $rowcount; //this is the value i want to publish on a HTML <label>
}
?>
If you want to output the results in a table you could do like this:
print "<table>";
while($row = mysqli_fetch_assoc($result)) {
print "<tr><td>".$row['ID_Vote']."</td></tr>";
}
print "</table>";
The same goes if you just want to print the amount of rows:
print "<table>";
print "<tr><td>".$rowcount."</td></tr>";
print "</table>";
Another way of doing it could be to end php:
<?
// Some code
?>
<table>
<tr>
<td><?=$rowcount;?></td>
</tr>
</table>
<?
// More php
?>
You can have a read here
Guys i found the solution to my problem, all the query was ok like i said. But the extension of my webpage was .HTML and when i change it to .php it worked. Now i got the website running with HTML and php code using a .php extension instead .html
Thanks for your attention.
I have creating a little section on my webpage that changes randomly everytime the webpage opens. The code looks like this.
<div id ="quote-text">
<?php
mysql_connect("localhost", "xxxxxxx", "xxxxxxx") or die(mysql_error());
mysql_select_db("xxxxxxx") or die(mysql_error());
$result = mysql_query("SELECT * FROM quotes WHERE approved=1 ORDER BY RAND () LIMIT 1")
or die(mysql_error());
while($row = mysql_fetch_array( $result )) {
echo "<img src=http://www.xxxxxxxxxx.com/images/".$row['image'] ." width=280px ><br>";
echo '<span class="style2">'.$row['quote'].'</span class>';
echo "<tr><td><br>";
echo "<tr><td>";
}
echo "</table>";
?>
</div>
What do I need to do to make this change every 5 seconds randomly withoutrefreshing the whole page?
thank you
You will need to make an AJAX call to change content on the page without refreshing.
Check out the W3Schools tutorial here: http://www.w3schools.com/ajax/ajax_intro.asp
Or even better use the mozilla tutorial:
https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
I'd say the most optimized solution would be to use a solution that makes use of both PHP, and javascript/Jquery.
First off it I would avoid to make an AJAX call to a PHP script every 5 seconds..
Instead you could make one call every X number of minutes and get a set of 12X images.
I would then use javascript, with setInterval to have the client change the image.
Halfway through, you can make another call to the PHP script to add new elements to your set of images, and remove the previous.
An approach like this would reduce overhead both clientside and serverside.
Update: Below a rough implementation of this method
Javascript:
<?php
if(isset($_GET['getBanners']))
{
header('Content-Type: application/json');
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("stackoverflow2") or die(mysql_error());
$json_rows = array();
$result = mysql_query("SELECT * FROM quotes WHERE approved=1 ORDER BY RAND () LIMIT 12;")
or die(mysql_error());
$element = 0;
while($row = mysql_fetch_array( $result )) {
$json_rows[$element] = $row['image'];
$element++;
}
print '{"dataVal":'.json_encode($json_rows).'}';
return;
}
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script>
//alert('test1');
var randomBanners = new Array ( );
var currentBannerIndex = 0;
function readNewBanners(startElement, numElements)
{
$.getJSON('http://127.0.0.1/stackoverflow/Banner.php?getBanners=1', function(data) {
for (var i = startElement; i < data.dataVal.length && i<startElement + numElements ; i++) {
randomBanners[i] = data.dataVal[i];
}
});
}
function refreshBannerImage()
{
if(document.getElementById('banner') == undefined) return;
document.getElementById('banner').innerHTML = ("<img src='"+randomBanners[currentBannerIndex]+"'/>");
currentBannerIndex = (currentBannerIndex+1)%12;
}
$( document ).ready(function() {
readNewBanners(0, 12);
setInterval(function() {
readNewBanners(0, 12);
}, 60000);
setInterval(function() {
refreshBannerImage();
}, 500);
});
</script>
</head>
<body>
<div id="banner">
Banner Here
</div>
</body>
</html>
SQL:
create table quotes
(
image varchar(10),
approved int
);
insert into quotes values ('http://dummyimage.com/600x400/000/fff&text=1',1);
insert into quotes values ('http://dummyimage.com/600x400/000/fff&text=2',1);
insert into quotes values ('http://dummyimage.com/600x400/000/fff&text=3',1);
etc...
You need to use AJAX for that. I suggest you to use the jQuery or a similar framework. Here is a nice example of what you want How to update a specific div with ajax and jquery. Add a setInterval() call like in this post http://forum.jquery.com/topic/jquery-setinterval-function and you are done.
I am trying to show the results of the status of a bidding item using jQuery every second on every row in MySQL table, however only the result of the last row of the table is returned.
<?php
$query = "SELECT item, description, price, imageData, status, username, item_id FROM items";
$result = mysql_query($query) or die(mysql_error());
$z=0;
while($row = mysql_fetch_array($result))
{
//echo other columns here//
echo "<td><div id=status$z></div></td>";
?>
<script type=text/javascript>
function updatestatus(itemnum)
{
var url="updatestatus.php?auc=<?php echo $row['item_id']; ?>";
jQuery('#status' + itemnum).load(url);
}
setInterval("updatestatus(<? echo $z?>)", 1000);
</script>
<?
$z++;
}
?>
When I view source in the browser, the values for #status and auc for every row are correct. What am I missing here?
Here's the code for updatestatus.php
<?php
session_start();
require_once("connect.php");
$id = $_GET['auc'];
$getstatus = mysql_query("SELECT status FROM items WHERE item_id = '$id' ");
$row = mysql_fetch_array($getstatus);
echo"$row[status]";
?>
Everything looks good, save for the fact that it looks like you're creating multiple references to your updatestatus() function.
In Javascript, if you create multiple functions with the same name, calling them will only result in one of them running, usually the first or last one (depending on the implementation), so all the code you need to run in those functions needs to sit together in one function body.
If you're determined to use the code you've created, you'd need to throw all those update calls into one function body. There would be better ways to achieve what you need, but doing it with the code you've created, this would probably work better:
<?php
$query = "SELECT item, description, price, imageData, status, username, item_id FROM items";
$result = mysql_query($query) or die(mysql_error());
$javascript = "";
$z=0;
while($row = mysql_fetch_array($result))
{
//echo other columns here//
echo "<td><div id=status$z></div></td>";
// build the javascript to be put in the function later over here...
$javascript .= "jQuery('#status". $z ."').load('updatestatus.php?auc=". $row['item_id'] ."');";
$z++;
}
?>
...and then further down the page, create the javascript (modified slightly):
<script type=text/javascript>
function updatestatus()
{
<?php echo $javascript; ?>
}
setInterval(updatestatus, 1000);
</script>
So you're basically building up the Javascript that you'll need in your function, echoing it out inside the function body, and then setting the interval will call all that code, in this case, every second.
Like I said, there are definitely more efficient ways to achieve what you're trying to do, but this should work fine for now. I hope this makes sense, but please let me know if you need any clarity on anything! :)
I don't see that you're populating data using a incrementor. Is this supposed to be adding content to a page or replacing the content? from what it looks like it will just display one item, and then replace that one item with the next until it's done, which is why you see only the last row.
OR ...
the jquery update isn't being fed the $i variable .. change the function to
function updatestatus(itemnum) {
and then jquery echo to jQuery('#status' + itemnum).load(url);
then you can add the on-click/ or whatever to include the number
onclick='updatestatus("1")'
on the other hand you might be needing to pass the total number of items to the function and then creating an if there to cycle through them (not tested, but you get the idea i hope)
function updatestatus(numitems) {
var url = "";
var itemID = "";
for (i = 1; i <= numitems; i++) {
itemid = getElementById('#status'+numitems).getAttribute("itemID")
url="updatestatus.php?auc="+itemID;
jQuery('#status'+numitems).load(url);
}
}
setInterval("updatestatus()", 1000);
and the html element for "#status1" as created by the PHP should look like this:
<div id="status1" itemid="23455">
</div>
I have this function http://jsfiddle.net/wnFsE/ . As you can see every time the user writes a languages on the textfield and then hits the button add a new language is added to the list. Then when the user hits save, all the info is sent with POST.
Until now, everything is ok. BUT, when the user sends the info, the info is stored on my MySQL database. So, every time when the user comes again to the page, he needs to see the languages already saved in the last session.
In my PHP script every time the user comes, I retrieve the languages from my database, but I don't know how to add them to the list. The solution would be call the $("#add").click(function() { from the PHP script who retrieve the data from the MySQL, but I don't know how to do this.
If it serves for any help, this is the simple PHP function which retrieves the languages from the user:
function list_lang() {
$this->DBLogin();
$result = mysql_query("SELECT * FROM ".table_lang." WHERE id_user=1");
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo $row['lang']." ".$row['level']."<br>";
//instead of the echo, here will be the call to jquery (if possible)
}
}
A simple soloution:
$buildHTML = '';
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$buildHTML .= '<li>'.$row['lang'].'<input type="hidden" name="languages[]" value="'.$row['lang'].'" />Remove</li>';
}
And then have
<script type="text/javascript">
var UserLangs = <?php echo $buildHTML; ?>;
$('#langs').append(UserLangs);
</script>
You can do this way:
<?php
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<script type="text/javascript">
...
...
listitem_html += <?php echo $row['lang']. $row['level'] . '<br>'?>;
...
...
</script>
<?php
}
?>
I am creating a table to display on a web page and that table is populated from data in a MySQL database. I am trying to do a couple of things that are making it difficult for me.
First I am trying to have call the PHP code that exists in a separate file in HTML via JavaScript. I think I have that working right but I am not 100% sure (because the table will not display). I think it is working right because some of the code for the table (which is in the PHP file) displays in FireBug.
Second I am trying to make it so the rows alternate colors for easy viewing too. My PHP code so far is below. The table does not display at all in any browser.
$query = "SELECT * FROM employees";
$result = mysql_query($query);
$num = mysql_num_rows($result);
echo '<table>';
for ($i = 0; $i < $num; $i++){
$row = mysql_fetch_array($result);
$id = $row['id'];
$l_name = $row['l_name'];
$f_name = $row['f_name'];
$ssn = $row['ssn'];
$class = (($i % 2) == 0) ? "table_odd_row" : "table_even_row";
echo "<tr>";
echo "<td class=" . $class . ">$wrap_id</td>";
echo "<td class=" . $class . ">$wrap_l_name</td>";
echo "<td class=" . $class . ">$wrap_f_name</td>";
echo "<td class=" . $class . ">$wrap_ssn</td>";
echo "</tr>";
}
echo '</table>';
mysql_close($link);
}
EDIT
To answer a few questions:
#controlfreak123, I am not sure what you mean by "include ('filename_with_php_in_it')". As far as the page not being called to be parsed, I think it is being called and contact is being made. I pointed out in my original question that I believe this is true because FireBug shows the code for the table, and that code is in separate PHP file, thus communication between the HTML file and the PHP file must be taking place. Here is how I am calling the PHP file from the HTML file you if you care to know:
<script language="javascript" type="text/javascript" src="/Management/Employee_Management.php?action=Edit_Employee"></script>
#Matt S, I am not getting much in the way of output, in fact I didn't know I was getting anything at all until I looked at FireBug and saw that the PHP code (or some of it) was indeed being passed to the HTML file. The specific question is how do I get the data I want from my MySQL database and populate it into an HTML table via PHP. I can also confirm that employees does have data in it, two entries I put in for testing. I can try to put the code into its own file without the JavaScript as you suggested, but that would defeat my purpose since I want my HTML and PHP files to be separate, but I may try it just to see if the PHP code is good and to make sure the JavaScript isn't breaking it.
#Aaron, I am not sure what you are asking (sorry). The code is meant to populate create and populate a table on an HTML page.
Here is a full example of what you're looking for:
pull some data from mysql using php
put that data into an html table
apply alternating colored rows to the table
For the styling I cheat a little and use jquery which I find a bit easier then what you're trying to do.
Also, remember $row[field] is case sensitive. So $row[id] != $row[ID].
Hope this helps:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<style type="text/css">
tr.header
{
font-weight:bold;
}
tr.alt
{
background-color: #777777;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
$('.striped tr:even').addClass('alt');
});
</script>
<title></title>
</head>
<body>
<?php
$server = mysql_connect("localhost","root", "");
$db = mysql_select_db("MyDatabase",$server);
$query = mysql_query("select * from employees");
?>
<table class="striped">
<tr class="header">
<td>Id</td>
<td>Name</td>
<td>Title</td>
</tr>
<?php
while ($row = mysql_fetch_array($query)) {
echo "<tr>";
echo "<td>".$row[ID]."</td>";
echo "<td>".$row[Name]."</td>";
echo "<td>".$row[Title]."</td>";
echo "</tr>";
}
?>
</table>
</body>
</html>
Here's the table code only using PHP to alternate the styles like you're trying to do in your example:
<table class="striped">
<tr class="header">
<td>Id</td>
<td>Title</td>
<td>Date</td>
</tr>
<?php
$i = 0;
while ($row = mysql_fetch_array($query)) {
$class = ($i == 0) ? "" : "alt";
echo "<tr class=\"".$class."\">";
echo "<td>".$row[ID]."</td>";
echo "<td>".$row[Name]."</td>";
echo "<td>".$row[Title]."</td>";
echo "</tr>";
$i = ($i==0) ? 1:0;
}
?>
</table>
The reason your code is not executing is that you cannot include PHP with the Script tag. You must use PHP's include function, and the original page must be parsed as PHP.
<?php
include('./my_other_file.php');
?>
The starting of the coding is a little bit wrong. It should be:-
<?php
$query = "SELECT * FROM employees";
$result = mysql_query($query);
$num = mysql_num_rows($result);
echo '<table>';
if($num) {
while( $row = mysql_fetch_array($result) ) {
// all logic for each of the rows comes here
}
}
else {
// no rows fetched, so display proper message in a row
}
echo "</table>";
?>
The first time "mysql_fetch_array" function is used on a Resource Handler, after that it does not work properly. This answer may seem a bit vague, but I have seen it many times, so I always use a "while" or "do-while" loop for fetching multiple rows from DB.
Try using the above code, & see if any information crops up.