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>
Related
I wanna build a presence check for our choir in the style of tinder but not as complex.
The database contains names and file paths of pictures of the members. When you click on the "present" or "not present" button, the next picture and name should be shown. In the background, the database table should be updated with true/false for presence. (this will be done later)
My problem is that it almost works, but instead of showing one member, it shows all members with their pictures in one single page.
I understand that I could fire with Javascript to continue and paused php-function but I don't get the clue how.
I tried "break" in the php and call the function again but that didn't work.
<?php
$conn = new mysqli(myServer, myUser, myPass, myDbName);
$sql = "SELECT * FROM mitglieder";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<img class='pic' src='" .$row["folder"]. "/" .$row["img"]. "'><br>" ;
echo "<div id='name'>" .$row["vorname"]. " " .$row["name"]. "</div> <br>";
echo "<img src=''img.png' id='present' onclick='isPresent()'>";
}
} else {
echo "0 results";
}
$conn->close();
?>
<html>
<script>
$( document ).ready(function() {
console.log("Ready");
);
</html>`
You can use php function
mysqli_fetch_all()
assign it on the variable outside the while loop and loop or access the indexes in your code.
For Example:
$data = mysqli_fetch_all();
echo $data[0]['name'];
foreach($data as $item)
{
echo $item['name'];
}
You need a way to establish a "state" between your web page and the PHP backend so that you can step through the data. I suggest something like this:
Use an auto-increment integer primary key for the database. That way you can access the data in index order. Let's name the column id
Have your JS code send a form variable - named something like LAST_ID to the PHP in your get. i.e http://someurl.com/script.php?LAST_ID=0
On your first call to the server, send LAST_ID = 0
In your PHP code, fetch the value like this: $id = $_GET('LAST_ID');
Change your SQL query to use the value to fetch the next member like this:
$sql = sprintf("SELECT * FROM mitglieder where id > %d limit 1", $id); That will get the next member from the DB and return only 1 row (or nothing at the end of data).
Make sure to return the id as part of the form data back to the page and then set LAST_ID to that value on the next call.
You can use a HTTP POST with a form variable to the server call that sets that member id to present (maybe a different script or added to your same PHP script with a test for POST vs GET). I suggest a child table for that indexed on id and date.
I hope that puts you in a good direction. Good luck
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 hope someone can help me, I have created a simple html form with drop down menu's, the drop down menus are populated from a mysql data base, the user must select from two drop downs and this will then display the data ( both selections make the sql query)
This all works correctly within the HTML however I am trying to jazz it up a bit and have the output display within a jquery colorbox (popup).
I am not sure how to format the syntax for the jquery function .. this is what I have so far
<script>
$(document).ready(function(){
$(".inline").colorbox({inline:true, width:"50%"});
$("input#formsubmit").colorbox({href: function(){
var url = $(this).parents('form').attr('action');
return url;
}, innerWidth:920, innerHeight:"86%", iframe:true});
});
</script>
This correctly launches the colorbox pop up and fires the php "action" from my form but the $_POST attributes are not sent across and I just get an unidentified index error from mysql.
Can some one please help me ?
Im sure its something simple, but I cant figure it out.
Many thanks
Adding PHP ...
<?php
mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("verify") or die(mysql_error());
$result = mysql_query("SELECT Entitlement FROM products WHERE ProductName = '$_POST[product]' AND CustomerType = '$_POST[customer]'")
or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row['Entitlement'] ;
echo "<br />";
}
?>
Can you please tell how may this code works with you :)
<?php $result = mysql_query("SELECT Entitlement FROM products WHERE ProductName = '$_POST[product]' AND CustomerType = '$_POST[customer]'");?>
You have 2 error the first one the single quote beside the index in your post variable and must be like this $_POST['product'],$_POST['customer'] then the second error is that you must encapsulate your variable inside the string as following {$_POST['product']},{$_POST['customer']}
Try these work around then tell me the result :)
try this
<?php
// Checking for valid post data
if (isset($_POST['product']) && isset($_POST['customer']) && !empty($_POST['product']) && !empty($_POST['customer'])) {
// Cleaning post data
$proudct = mysql_escape_string($_POST['product']);
$customer = mysql_escape_string($_POST['customer']);
// db connnection
mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("verify") or die(mysql_error());
// Quering
$result = mysql_query("SELECT Entitlement FROM products WHERE ProductName = '$proudct' AND CustomerType = '$customer'") or die(mysql_error());
// Printing result
while ($row = mysql_fetch_array($result)) {
echo $row['Entitlement'];
echo "<br />";
}
}
?>
Hello i am new to php and i have tried to find a piece of code that i can use to complete the task i need, i currently have a page with a form set out to view the criteria of a course. also i have a dropdown menu which currently holds all the course codes for the modules i have stored in a database. my problem is when i select a course code i wish to populate the fields in my form to show all the information about the course selected. The code i am trying to get to work is as follows:
<?php
session_start();
?>
<? include ("dbcon.php") ?>
<?php
if(!isset($_GET['coursecode'])){
$Var ='%';
}
else
{
if($_GET['coursecode'] == "ALL"){
$Var = '%';
} else {
$Var = $_GET['coursecode'];
}
}
echo "<form action=\"newq4.php\" method=\"GET\">
<table border=0 cellpadding=5 align=left><tr><td><b>Coursecode</b><br>";
$res=mysql_query("SELECT * FROM module GROUP BY mId");
if(mysql_num_rows($res)==0){
echo "there is no data in table..";
} else
{
echo "<select name=\"coursecode\" id=\"coursecode\"><option value=\"ALL\"> ALL </option>";
for($i=0;$i<mysql_num_rows($res);$i++)
{
$row=mysql_fetch_assoc($res);
echo"<option value=$row[coursecode]";
if($Var==$row[coursecode])
echo " selected";
echo ">$row[coursecode]</option>";
}
echo "</select>";
}
echo "</td><td align=\"left\"><input type=\"submit\" value=\"SELECT\" />
</td></tr></table></form><br>";
$query = "SELECT * FROM module WHERE coursecode LIKE '$Var' ";
$result = mysql_query($query) or die("Error: " . mysql_error());
if(mysql_num_rows($result) == 0){
echo("No modules match your currently selected coursecode. Please try another coursecode!");
} ELSE {
Coursecode: echo $row['coursecode'];
Module: echo $row['mName'];
echo $row['mCredits'];
echo $row['TotalContactHours'];
echo $row['mdescription'];
echo $row['Syllabus'];
}
?>
however i can only seem to get the last entry from my database any help to fix this problem or a better way of coding this so it works would be grateful
Thanks
The main error is in your final query, you're not actually fetching anything from the query, so you're just displaying the LAST row you fetched in the first query.
Some tips:
1) Don't use a for() loop to fetch results from a query result. While loops are far more concise:
$result = mysql_query(...) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
...
}
2) Add another one of these while loops to your final query, since it's just being executed, but not fetched.
For me i would use some javascript(NOTE: i prefer jQuery)
An easy technique would be to do this(going on the assumption that when creating the drop downs, your record also contains the description):
Apart from creating your dropdown options like this <option value="...">data</option>, you could add some additional attributes like so:
echo '<option value="'.$row['coursecode'].'" data-desc="'.$row['description'].'">.....</option>
Now you have all your drop down options, next is the javascript part
Let's assume you have included jQuery onto your page; and let's also assume that the description of any selected course is to be displayed in a <div> called description like so:
<div id="course-description"> </div>
<!--style it how you wish -->
With your javascript you could then do this:
$(function(){
$("#id-of-course-drop-down").change(function(){
var desc = $(this).children("option").filter("selected").attr("data-des");
//now you have your description text
$("#course-description").html(desc);
//display the description of the course
}
});
Hope this helps you, even a little
Have fun!
NOTE: At least this is more optimal than having to use AJAX to fecch the description on selection of the option :)
I'm working on a website and am pulling category names from a db table (category_names). I then display them on the website using php on to an html unordered list. I want to limit the number of category_names and then using jquery(or anything else but I prefer jQuery) retrieve more category_names and add a less button to go back.
I hope I made this question easy to understand, and thank you for any help!
Basically use AJAX to pull in more. Start off by loading in a few by using LIMIT.
<ul id="categories">
<?php
$res = mysql_query('SELECT * FROM `category_names` LIMIT 10'); // change limit to suit
while ($row = mysql_fetch_array($res)) {
echo '<li>'.$row['name'].'</li>'; // or whatever your field is called
}
?>
</ul>
<span id="loadmore" num_loaded="10">Load More</span>
Then use the following jQuery to load more:
$('#loadmore').click(function() {
var loaded = $(this).attr('num_loaded');
$.ajax({
url:'load_categories.php',
type:'get',
data:{'from':loaded,'to':loaded+10},
success: function (res) {
var categories = $.parseJSON(res);
categories.each(function() {
$('#categories').append('<ul>'+this+'</ul>');
});
$('#loadmore').attr('num_loaded',loaded+10);
}
});
});
Finally you'll need to create the PHP page that the AJAX calls - load_categories.php
<?php
if (!isset($_GET['from'])) exit;
if (!isset($_GET['to'])) exit;
$from = $_GET['from'];
$to = $_GET['to'];
$diff = $from-$to;
// connect / select db
$res = mysql_query('SELECT * FROM `category_names` LIMIT '.$from-1.','.$to.';');
$arr = array();
while ($row = mysql_fetch_array($res)) {
array_push($arr,$row['name']);
}
echo json_encode($arr);
?>
There are a number of different approaches that work better or worse depending upon your needs.
Approach 1 (simpler, less efficient, scales poorly): execute the full query, and store all of the results on the DOM, just hiding them using jQuery (jQuery expander is a simple plugin you may want to try out, though I have found it limiting in customization).
Approach 2 (more complicated, but more efficient/scalable, also faster): Use MySQL limit, you can actually send a second mysql request on click, however, you would want to make sure this is asynchronous so as to not delay the user's interactions.
http://php.about.com/od/mysqlcommands/g/Limit_sql.htm
This is similar to: PHP/MySQL Show first X results, hide the rest
Or you could do something simpler:
$get = mysqli_queury ($link, "SELECT * FROM db_name WHERE blank='blank' LIMIT 5"
if (isset($_POST['button']; {
$get = mysqli_query ($link, "SELECT * FROM db_name WHERE blank='blank' LIMIT 10"
}
?>
<form action="showmore.php" method="POSt">
<input type="button" id="button" name="button">
</form>
Hope that helps!
Use a datagrid with pagenation. I think datatable JQuery pluggin will work well for you