Hi I have the following code and was wondering if its possible to make the PHP part repeat so the javascript var is kept upto date even if a new row has been add to the table?
<script type="text/javascript" >
var total_rows = [];
<?php
$con = mysql_connect("localhost", "user", "password");
$total = mysql_query("SELECT * FROM table");
$num_rows = mysql_num_rows($total);
?>
var total_rows = "<?php echo $num_rows ; ?>";
</script>
Not directly, because PHP is server side only, and has finished executing by the time your JS is executed.
While you could check it without reloading the page using AJAX, I would question whether what you are doing is useful anyway - the client should not care about the number of rows in a table as a general rule - the only real exception being if you are making a database management page, and even then it's usefulness is debatable. If you need to update/delete a row from client input, all you need is the ID of the row, and if you are adding one you should let the database generate a row ID for you with an auto-incrementing primary key.
I suspect you would be better looking at your application's implementation as whole if you have reach a point where you feel you need this information at the client side.
You can use AJAX to update parts of your page without reloading the entire page. You should look into that. A good tutorial to start will be http://www.w3schools.com/php/php_ajax_intro.asp.
Repeating the PHP code in HTML itself is not possible, because the PHP code is not available in the HTML page. The HTML page is the result of executing a PHP script.
You would need to use AJAX to hit a file which does the PHP select and returns the desired row.
You would have to refresh your query to get the latest count, so I would do something like this. this example uses jquery: http://api.jquery.com/jQuery.get/
function get_updated_rows(){
$.get('count.php', function(data) {
var total_rows = data;
})
return total_rows;
}
You count.php file would contain the php:
<?php $con = mysql_connect("localhost", "user", "password");
$total = mysql_query("SELECT * FROM table");
$num_rows = mysql_num_rows($total);
echo $num_rows;
?>
then when you need the updated count, just use your function: get_updated_rows();
Related
I am doing this animation tool where I fetch a value from my database and then a picture will animate to a certain position. My question is if it is possible to retrieve data constantly or like every 5 seconds?
Somehow like this:
while(autoretreive){
$data = mysql_query("select * from ......");
}
UPDATED from here
Thanks for your answers! Made it a little bit clearer what to do! Maybe I can explain better what I'm doing in my code.
I am doing this animation program as said, where balls with information is moving around to different locations. I have one value that will be updated frequently in the database, lets call it 'city'.
First at previous page I post the balls of information I want based on the 'city' and I do like this (simplified):
$pid = $_POST['id'];
$pcity[0] = $_POST['city'];
$pcity[1] = $_POST['city'];
$pcity[2] = $_POST['city'];
//...
$while(autoretrieve) { // HOW TO?
$data = mysql_query(select * from table where city == $pcity[0] OR $pcity == [1] //...);
while($rows = mysql_fetch_array($data)){
$city = $rows['city'];
$id = $rows['id'];
if($city == example1){
"animate to certain pos"; //attached to image
}
else if($city == example2){
"animate to certain pos"; //attached to image
}
}
}
So for every update in the database the image will animate to a new position. So a time interval of 5 seconds would be great. I'm not an expert in coding so sorry for deprecated code. Not so familiar with AJAX either so what is going to be imported to the code? It is also important that the page is not reloading. Just the fetch from database.
you can do it with ajax and javascript
make one javascript function which contains ajax code to retrive data from database
and at your page load using setTimeout call your ajax function at every 5 second
You can use sleep function to control how often you want to fetch data.
while(autoretreive){
$data = mysql_query("select * from ......");
//output your data here, check more in link about server sent events bellow
sleep(5);
}
Since you haven't specified how you plan to access data I'm writing this answer assuming Server-Sent Events as they are only ones that make sense according to your question.
Now all this was according to your question which wasn't very clear on how do you plan to use data. Again you'll most likely want to fetch data using ajax, but Server Sent Events can also be a good way you could achieve this.
And don't use mysql_* it's deprecated, switch to PDO or mysqli_*
I have this while loop, that basically loops through a lot of records in a database, and inserts the data in another:
$q = $con1->query($users1) or die(print_r($con2->errorInfo(),1));
while($row = $q->fetch(PDO::FETCH_ASSOC)){
$q = $con2->prepare($users2);
$q->execute(array($row['id'], $row['username'])) or die(print_r($con2-errorInfo(),1));
}
(The script has been shortened for easy reading - the correct one has a much longer array)
I would like to do this more graphical, and show a progress bar on how far it has went, instead of just seeing a page loading for a few minutes (there are ~20.000 rows in this one - I have tables with much more data)
I get that you could get the total number from the old database, and I could also easily put the current number into a variable like this:
$q = $con1->query($users1) or die(print_r($con2->errorInfo(),1));
$i = 0;
while($row = $q->fetch(PDO::FETCH_ASSOC)){
$q = $con2->prepare($users2);
$q->execute(array($row['id'], $row['username'])) or die(print_r($con2-errorInfo(),1));
$i++;
}
But now I need to actually fetch $i and display it - or something like it.
How is this "easily" done?
The code for the progress bar can either be in the same document as the while loop, or in another if easier.
You can do a "master" file that does an ajax to this first file to run a single query. You could get all the entry id's in this master file, and then pass it as a parameter to the second file that does a single query. Store these ids in a javascript array.
Create a function that does this, and when the first ajax is done, move to the second element of the id array, and do another ajax with a second parameter. That's how magento imports are done by the way :)
If you need further explanations, let me know, I tried my best to explain, but may have not been perfectly clear.
// you generate this javascript array using php.
// let's say you have all the ids that have to be processed in $Ids php array.
Ids = [<?php echo implode(',', $Ids); ?>];
function doAjax(i) {
$.ajax({ // using jquery for simplicity
'url': "ajax.php?id=" + Ids[i],
}).done(function(){
if ( i >= 0 ) {
// at the point you know you're at ((Ids.length-i)/(Ids.length) * 100) percent of the script
// so you can do something like this:
// $('.progressbar').css('width', ((Ids.length-i)/(Ids.length) * 100) + '%');
doAjax(i-1);
}
});
}
doAjax(Ids.length); // starting from the last entry
So, just to explain what this does. It starts by declaring a global javascript array that has all the ids that will need to be changed.
Then I declare a recursive ajax function, this way we can make sure that only one ajax runs at any single time (so the server doesn't blow up), and we can have a fairly accurate progress. This ajax function does the following:
Sends a request to ajax.php?id=xxx - where xxx is one of the ids in the javascript array.
In the file, we get the id ($_GET['id']), you take it from the old database, and insert it in the new one. This is only for one entry.
when the ajax is done, it goes to the done() function. Since we start the doAjax() function with the last element, we do the next iteration doAjax(i-1). Since we're going backwards in the array, we check if the key is positive. If it's not, the script will stop.
That's about it.
You can't. The php is first interpreted by the server and then send to the user as HTML-Code.
The only possibility would be creating a html-page and call the php-script with AJAX.
i am new to Javascript and i have created the code below it works fine no problem at all however i want to know what is i want to pull the image dynamically using php and javascript from mysql database how can i refactor my code bellow. thanks in advance for your contribution.
var myimage = document.getelementById("mainImage");
var imageArray =["images/overlook.jpg","images/garden.jpg","images/park.jpg"];
var imageIndex =0;
function changeimage(){
myimage.setAttribute("src",imageArray[imageIndex]);
imageIndex++;
if(imageIndex >= imageArray.length){
imageIndex = 0;
}
setInterval(changeimage, 5000);
One of several options.
Query the database for the column with the URL of the images.
$query = mysql_query("SELECT url FROM images");
Then something like this to get an array out of it:
$images = array();
while($row = mysql_fetch_array($query)){
$images[] = $row['url'];
}
Then generate this string (that you use in the Javascript provided):
var imageArray = ["images/overlook.jpg","images/garden.jpg","images/park.
using the array you retrieved from the database. You could use json_encode in PHP for this if you don't want to mess around with error prone string building.
$imagesAsJsonArray = json_encode($images);
Echo it. Done.
Not the most elegant of solutions. But it gives you something to play with. Check out a few PHP tutorials online and you'll soon get the hang of it.
Two choices:
Using PHP when your page is created, put an array of images in the page and use page-level javascript to cycle among them.
Using Ajax in the page, call from the page to the server to get the next image and then use client-side javascript to make that returned image visible on the page.
oops I was thinking something when a question was asked...ok I do have near about 200000 datas in my MySQL database and counting.
so what I want is to show that number in real time or say within some interval...
for example the current status is 2000000
after, let's say, 5 hours it may be 2000156
You want to use mysql count() function
Yep as pervious answer you can use the mysql count() function, usage is as such:
SELECT count(*) FROM table WHERE condition='value';
I wouldn't advise using this frequently, if all it does is return a count of the tuples in your database.
Infrequent use should be fine.
in case you mean the row count of a table.
in your html (or php) page write this somewhere between your head tags:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script> // you don't have to write this line if you already included jquery
<script type="text/javascript">
$(document).ready(function() {
function updateDataCount(){
$('#datacount').load('getDataCount.php');
}
updateDataCount(); //set the datacount as soon as the page is loaded
setInterval( "updateDataCount()", 10000 ); //update the datacount every 10 seconds
});
</script>
Then create an element on your page, where you want to display your datacount in:
<div id = "datacount"></div>
Finaly you need to create the file getDataCount.php which will look like this:
<?php
//put your logic here to connect to your database
$query = "SELECT count(*) FROM [your table]";
$numrows = mysql_result($query, "0");
print $numrows;
?>
What Engine do you use MyISAM or InnoDb? Do you really nean get count in real time or you could get data a little bit obsolete?
I think using Count all the can be very expensive if you use InnoDb engine. For example, MyISAM engine always stores the number of columns, so Count query is very fast.
I am trying to call back the value of content_columns to jquery.
PHP CODE:
if($act=="getcol"){
$pid=$_GET['pid'];
$domain_id = 1;
$PAGEresult = mysql_query("SELECT * FROM pages WHERE domain_id='$domain_id' AND id='$pid' ORDER BY id DESC");
$PAGErow = mysql_fetch_array($PAGEresult);
echo json_encode($PAGErow['content_columns']);
}
jQuery
$.get("get_actions.php?act=getcol&pid="+pid, function(data){
alert(data);
});
Can someone lead me down the right path please.
If by "same string" it is possible that it is cached. You can disable caching with jQuery's ajax library that you are using. You can also send a different query string such as with the system time to ensure you don't get a cached results. You can also use POST.
You will only ever get one result from that query. If you want multiple results, you need to iterate over mysql_fetch(). If you only want one result, add LIMIT 1 to your query. Otherwise it is incredibly wasteful. Finally, why use SELECT *? Use SELECT content_columns ..