I have an events calendar.
Each event has a different location on the calendar.
Every time page loads, I empty the event location table and I write the location of the event to the table.
event location table looks like this
eventid location
1 1
2 2
3 1
4 1
5 1
6 2
7 3
8 4
9 5
There are some other variables involved but it is pretty much like this. Each event needs to know the previous event's location so that it can decide its own location.
There are also different views of this calendar and each view use the same technique so it is not the healthiest way to solve this.
The question is;
Is there any way to store this table's data on a cache or something like that instead of re-writing the table every single time.
There are at least two approaches you can take to cache this data. The easiest is to serialize() the data and store it in your database. When you need to retrieve the database, query it from the database, unserialize() it, and use it as before.
As second approach is to add memcache to your PHP installation and access your data via the memcache functions. Example:
<?php
$memcache = new Memcache;
$memcache->connect('localhost', 11211) or die ("Could not connect");
$version = $memcache->getVersion();
echo "Server's version: ".$version."<br/>\n";
$tmp_object = new stdClass;
$tmp_object->str_attr = 'test';
$tmp_object->int_attr = 123;
$memcache->set('key', $tmp_object, false, 10) or die ("Failed to save data at the server");
echo "Store data in the cache (data will expire in 10 seconds)<br/>\n";
$get_result = $memcache->get('key');
echo "Data from the cache:<br/>\n";
var_dump($get_result);
?>
Related
I am running a couple of live and vod streams being segmented with ffmpeg. I run one channel per cloud server. I have a central, more robust server which i use for various tasks one of those task being ingesting the main m3u8 playlist and storing the segment names and creation times in a database.
The segments are created about every 8 seconds currently for 8 channels.
This means that every 8 seconds i call the playlist.m3u8 (which is on a remote server) and store the information for each segment in the database.
This allows me to quickly create the vod (Select from channel 1 between time and time).
However, once or twice the database seems to have stopped working and I need to repair it before it can take new information.
I am wondering, am I hitting it too hard? Is there a better way?
My statement opens a new connection, checks if the entry already exists, if not it will enter it, then it closes the connection.
I do this once per channel per 8 seconds.
This feels like it could be better but I don't quite know how. Should I / can I keep the connection open maybe? Maybe its not a problem at all.
Anyone have any advice?
If you need more information just ask.
Query:
$conn = new mysqli($servername, $username, $password, $dbname);
$eight = date('Y-m-d', strtotime("-8 day"));
$vq = "SELECT * FROM `".$channels['channels'][$id]['fo_id']."`
WHERE `segment_name` = '".$oline."'";
$query = mysqli_query($conn, $vq);
if(mysqli_num_rows($query) == 0){
$sql = "INSERT INTO `".$channels['channels'][$id]['fo_id']."`
(`segment_name`, `server`, `created`, `lenght`)
VALUES
('".$oline."', '".$channels['channels'][$id]['server']."',
'".date("Y-m-d H:i:s", $date)."', '".$otime."')";
$conn->query($sql);
}
$query = mysqli_query($conn, "DELETE FROM `".$channels['channels'][$id]['fo_id']."`
WHERE `created` < '".$eight." 00:00:00'");
$conn->close();
<?php
$host= "localhost";
$user= "xxxxxx";
$pass= "xxxx";
$db="xxxxxxx";
$connect= mysql_connect($host,$user,$pass);
if (!$connect)die ("Cannot connect!");
mysql_select_db($db, $connect);
$result = mysql_query("
SELECT
*
FROM
values
");
if($result){
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$url = $row['value'];
echo '<li><iframe src="http://xxxxxxx.xxxx/xxxx.php?value='.$url.'" width="300" height="100" scrolling="no" frameBorder="0""></iframe></li>';
}
}
?>
this is my php code I am using to get values from database. I want to use a time delay in each of the value.
like
http://xxxxxxx.xxxx/xxxx.php?value='.$url.'
wait 5 sec
http://xxxxxxx.xxxx/xxxx.php?value='.$url.'
wait 5 sec
and so on.
Is there any way I can do that.
Thanks.
wrong answer: use sleep(5) inside while().
right answer:
a) you should not use mysql_* functions
b) if you need a delay, get all rows, then output them one by one using JS.
OR:
c) again, using JS and ajax, query for new row every 5 seconds
If you'll stick to wrong answer, your script will die of timeout at ~6th row (in default php install)
You should understand client/server architecture better:
mysql query and your php-code is a server-side, it will not return any output to browser (your visitor), until its end, and you don't want your visitors to wait 30 or 300 seconds for the server to reply.
so only option you have is: query for new image every 5 seconds, or query them all and iterate over them.
There are many jquery/javascript tutorials on that subject.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
i need some little help .. i wanna fetch only new entry in my database without refresh my page..
ii have an php page which can display all record's of my database .. like someone entered new data in database i want to fetch only single entery .. don't fetch all entries of again .. i also read too many of articles about JSON ajax etc .. but no onehelps me about fetch only single entery . is here any way using xml or something's special to do this .. i don't have any idea how i can do it
thank you
A very general approach would be something like that:
On every page load run a script that checks every a certain time interval the database for new entries:
Javascript:
<script>
$(document).ready(function(){
setInterval(function(){
$.ajax({
type: 'POST',
url: 'ajaxfile.php'
}).success(function(response){
var response = $.parseJSON(response);
var username = response.username; //here we put hypothetical db column "username" in a variable
alert(username); //here we alert the "username" variable in order to verify the script. All other db columns can be called as: response.db_column_name
});
}, 10000); //interval time: 10000 milliseconds (10 seconds)
});
</script>
This script, combined with the following "ajaxfile.php" will display all database columns as: response.db_column
Before I give you my idea about the 'ajaxfile.php', please keep in mind that in order for this approach to work, you need to add an extra column to your db table (for example column: "seen" -that takes values 1 or 0 and having number 1 as default for every new row added). Since you didn't provide enough information, I will here assume that the database table is called "users" and -say- you want to monitor each new user registration in real time (with 10 seconds intervals).
PHP (ajaxfile.php)
<?php
//protect the file from un-authorized access
define('AJAX_REQUEST', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
if(!AJAX_REQUEST) {die();}
require("db_connect.php"); //a typical db connection function
$results = array(); //define the results variable
$query = mysql_query("SELECT * FROM users WHERE new_column = '1' ORDER BY id DESC LIMIT 1"); //here we query the db to fetch only the newest record -the one where column "seen" is "1"
while($res = mysql_fetch_assoc($query)){
$current_id = $res["id"];
mysql_query("UPDATE users SET new_column = '0' WHERE id = '$current_id' "); //update the record so it will appear as "seen" and will not be fetched again
$results[] = $res;
}
echo json_encode($results);
?>
In the above file, notice the first two lines which are there to protect the ajax file from direct "browser calls". It is quite a universal solution and can be used in all ajax files.
Finally, here is an example of the db_connect.php file:
<?php
define('DB_HOST', 'localhost'); // the database host
define('DB_PORT', '3306'); // the database port
define('DB_NAME', 'your_db_name'); // the database name
define('DB_USER', 'your_db_user'); // the database user
define('DB_PASSWORD', 'your_db_password'); // the database password
$conn = #mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die("Could not connect to the Database Server");
mysql_select_db(DB_NAME, $conn) or die("Could not find the Database");
?>
It is a very general approach indeed, but can cover a wide spectrum of applications with small modifications or additions.
I am sorry I could not be more specific -but your question was also a bit too "general"... Hope this helps you and others.
I'm trying to increment +1 impression every time an ad is displayed on my site, however the variable increments +2 to +3 arbitrarily. I've removed everything that's working correctly and I made a page with only this code in it:
<?php
require "connect_to_mydb.php";
echo 'Hello***** '.$testVariable=$testVariable+1;
mysql_query("UPDATE `imageAds` SET `test`=`test`+1 WHERE `id`='1'");
?>
Every time the page is refreshed the, test increments arbitrarily either +2 or +3 and my page displays Hello***** 1 (Just to show its not looping). Access is restricted to this page so it's not other users refreshing the page.
Also, id and test are int(11) in the DB.
My DB required connection has nothing in it that would interfere.
Edit
Here is an updated code:
<?php
require "connect_to_mydb.php";
mysql_query("UPDATE `imageAds` SET `test`=`test`+1 WHERE `id`='1'");
$sql = mysql_query("SELECT * FROM imageAds WHERE id='1' LIMIT 1");
$check = mysql_num_rows($sql);
if($check > 0){
$row = mysql_fetch_array($sql);
echo $row['test'];
}
?>
Increments by +2 everytime
Edit
This is whats in connect_to_mydb.php
<?php
$db_host = "*************************";
$db_username = "*********";
$db_pass = "**********";
$db_name = "**************";
mysql_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mysql");
mysql_select_db("$db_name") or die ("no database");
?>
Either there's a bug in MySQL's implementation of UPDATE, or you're doing something wrong in some code you haven't posted.
Hint: It's very unlikely to be a bug in MySQL. Other people would have noticed it.
From what you've shown, it looks like your page is being loaded multiple times.
This attempt to prove that the code is only being called once doesn't prove anything:
echo 'Hello***** '.$testVariable=$testVariable+1;
This will always print the same thing (Hello***** 1) even if you open this page multiple times because the value of $testVariable is not preserved across seperate requests.
This +2/+3 error is occurring only with Chrome and my Mobile Android browser and the code is solid. I looked to see if there is any issue with Chrome sending more than one http request (thx user1058351) and there is which is documented here:
http://code.google.com/p/chromium/issues/detail?id=39402
So since this way was unreliable I just completed a work around that is solid. Instead of including a PHP file that updates the amount of ad impressions on reload, I now have it so when the page loads, an AJAX request is sent to a separate PHP file which updates the ad stats and returns the appropriate data. The key I think is to send it through the JS code so only one http request can be sent to increment the data.
Thank you to all who responded especially user1058351 and Mark Byers (not a bug in MYSQL but possibly appears to be a bug in Chrome).
I'm trying to add some speed performance to a project I'm working on using memcache. However I'm having a problem with the following
public function sql_query($query){
$memcache = new Memcache;
$memcache->connect('localhost', 11211) or die ("Could not connect");
$memkey = md5($query);
$get_result = $memcache->get($memkey);
if ($get_result){
return $get_result;
} else {
$q = $this->mysqli->query($query);
$memcache->set($memkey, $q, false, 120) or die ("Failed to save data at the server");
if ($this->mysqli->error){
App::Error($this->mysqli->error);
}
return $q;
}
}
It is certainly putting something into memcached but I get this error when pulling it back out and use it as I would if it wasn't from the cache.
"Warning: mysqli_result::fetch_assoc(): Couldn't fetch mysqli_result"
Am I missing something? I'm sure I've used memcache before in a similar way without any issues.
You can not store all data-types into memcached (and other data-stores), one which most often does not work are resources Docs, for example a database link or a result identifier.
You stored such a value and on another request you pulled it out again. But as the database already is in another state, this resource does not work any longer. You get the error then.
Instead you need to store the result data from the query, that's static data you can put into memcache.