SELECT a.* b.* c.*
FROM TOPIC a, BOARD b, MSGS c
WHERE c.MessageID = 1 AND a.TopicID = c.MessageID AND b.BoardID = c.BoardID
How to memcache this data?
set_cache("MY_WACKY_QUERY_1", data) note: 1 is the message id
Now there are lots of places in the code which update these 3 tables (independantly of each other), so we need to del_cache("XXX_1"); whenever any of these updates and inserts affect MSGS, TOPIC, or BOARD data for, or relating to, the message with id 1
Is there an easy solution?
You can't delete data from memcached without knowing the exact cache key that was used to store it. There is no "index" or "key list" from which you can search for stored data.
One solution might be to make your cache lifetimes short enough so that stale data is mostly a non-concern.
Or maybe... I think I'm confused. To me, it kinda looks like you can do this.
<?php
$memcache = new Memcache;
$memcache->connect( 'memcache_host', 11211 );
// do select query here, store into $result
$memcache->set( 'MY_QUERY_1', $result, false, 600 );
// do another select query here, store into $result
$memcache->set( 'MY_QUERY_2', $result, false, 600 );
// Query here updates record with id of 1
$memcache->delete( 'MY_QUERY_1' );
Related
I have a curious issue that is happening on my system when I run a PHP program I created. I am taking data from two tables and doing a comparison of data from Table A with Table B. If the record is not in Table A, then write that record to Table B. I discovered that the program works fine but, at least one record has to be in Table B first. After my first successful run Table A will have 16000+ records in it, now Table B has 15000+ or so records. I understand that there is going to be a bit of time for this to process. The curious thing is I noticed my hard drive is losing free space as the program runs. I have tried manually running the garbage collection. I also looked where the session files are being stored, only to find a few files that are rather small in size. I also tried adjusting the length of time that session files are stored from 1440 seconds to 30 secs. When I say that I am "losing" free space, there is something that is filling up my hard drive. I have gone from having 6GB to 5.75GB, if I allow the program to run longer, I only lose more space. I have also tried just simply restarting my system and I only regain a small portion of the space I lost. At this point I am unsure what I need to do to stop this from happening. Here is a sample of my code below:
<?php
include('./connect_local_pdo.php'); //Includes DB Connection Script
ini_set('max_execution_time', 5400); //5400 seconds = 90 minutes
gc_disable();
try {
$tbl_a_data = $conn->prepare('SELECT col_a, col_b, col_c from table_a');
$tbl_a_data->execute();
$tbl_b_data = $conn->prepare('SELECT col_a, col_b, col_c from table_b');
$tbl_b_data->execute();
$tbl_b_array = $tbl_b_data->fetchAll(PDO::FETCH_ASSOC);
while($tbl_a_array = $tbl_a_data->fetch(PDO::FETCH_ASSOC)){
foreach ($tbl_b_array as $tbl_b_array2){
if ($tbl_a_array['col_a'] !== $tbl_b_array2['col_a']){
$stmt = $conn->prepare("INSERT INTO table_b
(col_a, col_b, col_c)
VALUES
(:col_a, :col_b, :col_c)");
$stmt->bindParam(':col_a', $tbl_a_array['col_a']);
$stmt->bindParam(':col_b', $tbl_a_array['col_b']);
$stmt->bindParam(':col_c', $tbl_a_array['col_c']);
$stmt->execute();
} else {
$stmt = $conn->prepare("update table_b
set
col_b = table_a.col_b,
col_c = table_a.col_c
from table_a
where table_b.col_a = table_a.col_a ");
$stmt -> execute();
}
}
}
gc_collect_cycles();
gc_mem_caches();
clearstatcache();
} catch (PDOException $a) {
echo $a->getMessage();//Remove or change message in production code
}
Any assistance with this will be greatly appreciated! As of this post I have lost 2 gigs of space running this program.
With your line
include('./connect_local_pdo.php'); //Includes DB Connection Script
I assume it is a Database on localhost.
The Database is growing with your entries. It will take space to add rows.
I am trying to source the structure and data from a sage line 50 database but am having trouble with my update/create script.
Basically, I am writing a tool so that the local intranet site can display data sourced from sage to normal employees without using up a sage login (orders due in/stock levels etc). I am having trouble with this because it seems that the Sage50 database was developed by total morons. There are no Unique keys in this database, or, more accurately, very very few. The structure is really old school you can find the structure on pastebin HERE (bit too big for here). You'll notice that there are some tables with 300+ columns, which I think is a bit stupid. However, I have to work with this and so I need a solution.
There are a few problems syncing that I have encountered. Primarily it's the fact ODBC can't limit statements to 1 row so I can check data type, and secondly, with there being no IDs, I can't check if it's a duplicate when doing the insert. At the moment, this is what I have:
$rConn = odbc_connect("SageLine50", "user", "password");
if ($rConn == 0) {
die('Unable to connect to the Sage Line 50 V12 ODBC datasource.');
}
$result = odbc_tables($rConn);
$tables = array();
while (odbc_fetch_row($result)){
if(odbc_result($result,"TABLE_TYPE")=="TABLE") {
$tables[odbc_result($result,"TABLE_NAME")] = array();
}
}
This produces the first level of the list you see on pastebin.
A foreach statement is then run to produce the next level with the columns within the table
foreach($tables as $k=> $v) {
$query = "SELECT * FROM ".$k;
$rRes = odbc_exec($rConn,$query);
$rFields = odbc_num_fields ($rRes);
$i = 1;
while($i <= $rFields) {
$tables[$k][] = odbc_field_name($rRes, $i);
$i++;
}
CreateTableandRows($k,$tables[$k]);
}
At the moment, I then have a bodged together function to create each table (not that I like the way it does it).
Because I can't automatically grab back one row (or a few rows), to check the type of data with get_type() to then automatically set the row type, it means the only way I can figure out to do this is to set the row type as text and then change them retrospectively based upon a Mysql query.
Here is the function that's called for the table creation after the foreach above.
function CreateTableandRows($table,$rows) {
$db = array(
"host" => '10.0.0.200',
"user" => 'user',
"pass" => 'password',
"table" => 'ccl_sagedata'
);
$DB = new Database($db);
$LocSQL = "CREATE TABLE IF NOT EXISTS `".$table."` (
`id` int(11) unsigned NOT NULL auto_increment,
PRIMARY KEY (`id`),";
foreach($rows as $k=>$v) {
$LocSQL .= "
".$v." TEXT NOT NULL default '',";
}
$LocSQL = rtrim($LocSQL, ',');
$LocSQL .= "
) ENGINE=MyISAM DEFAULT CHARSET=utf8";
echo '<pre>'.$LocSQL.'</pre>';
$DB->query($LocSQL);
}
I then need/want a function that takes each table at a time and synchronizes the data to the ccl_sagedata database. However, it needs to make sure it's not inserting duplicates, i.e. this script will be run to sync the sage database at the start or end of each day and without ID numbers INSERT REPLACE won't work. I am obviously implementing auto inc primary ID's for each new table in the ccl_sagedata db. But I needs to be able to reference something static in each table that I can identify through ODBC (I hope that makes sense). In my current function, it has to call the mysql database for each row on the sage database and see if there is a matching row.
function InsertDataFromSage($ODBCTable) {
$rConn = odbc_connect("SageLine50", "user", "pass");
$query = "SELECT * FROM ".$ODBCTable;
$rRes = odbc_exec($rConn,$query);
$rFields = odbc_num_fields ($rRes);
while( $row = odbc_fetch_array($rRes) ) {
$result[] = $row;
}
$DB = new Database($db);
foreach($result as $k => $v) {
$CHECKEXISTS = "SELECT * FROM ".$ODBCTable." WHERE";
$DB->query($CHECKEXISTS);
// HERE WOULD BE A PART THAT PUTS DATA INTO THE DATABASE IF IT DOESN'T ALREADY EXIST
}
}
The only other thing I can think to note is that the 'new Database' class is simply just a functionalised standard mysqli database class. It's not something I'm having problems with.
So to re-cap.
I am trying to create a synchronization script that creates (if not exists) tables within a mysql database and then imports/syncs the data.
ODBC Can't limit the output so I can't figure out the data types in the columns automatically (can't do it manually because it's a massive db with 80+ tables
I can't figure out how to stop the script creating duplicates because there are no IDs in the sage source database.
For those of you not in the UK, Sage is a useless accounting package that runs on water and coal.
The Sage database only provides data, it doesn't allow you to input data outside of csv files in the actual program.
I know this is a bit late but Im already doing the same thing but with MS SQL.
Ive used a DTS package that truncates known copies of the tables (ie AUDIT_JOURNAL) and then copies everything in daily.
I also hit a bit of a wall trying to handle updates of these tables hence the truncate and re-create. Sync time is seconds so its not a bad option. It may be a bit of a ball ache but I say design your sync tables manually.
As you rightly point out, sage is not very friendly to being poked, so id say don't try to sync it all either.
Presumably you'll need reports to present to users but you don't need that much to do this. I sync COMPANY,AUDIT_JOURNAL, AUDIT_USAGE, CAT_TITLE,CAT_TITLE_CUS, CHART_LIST,CHART_LIST_CUS, BANK,CATEGORY,CATEGORY_CUS,DEPARTMENT, NOMINAL_LEDGER,PURCHASE_LEDGER,SALES_LEDGER.
This allows recreation of all the main reports (balance sheet, trial balance, supplier balances, etc all with drill down). If you need more help this late on let me know. I have a web app called MIS that you could install locally but the sync is a combo of ODBC and the DTS.
OK you do not need to create a synchronisation script you can query ODBC in real time you can even do joins like you do in SQL to retrieve data from multiple tables. The only thing you cannot do is write data back to sage.
The High Level Idea:
I have a micro controller that can connect to my site via a http request...I want to feed the device a response as soon as a change is noted on the database...
Due to the the end device being a client ie micro controller...Im unaware of a method to pass the data to the client without having to set up port forwarding...which is heavily undesired ...The problem arise when trying send data from an external network to an internal one...Either A. port forwarding or B have the client device initiate the request which leads me to the idea of having the device send an http request to file that polls for changes
Update:
Much Thanks to Ollie Jones. I have implimented some of his
suggestions here.
Jason McCreary suggested having a modified column which is a big
improvement as it should increase speed and reliability ...Great
suggestion! :)
if the database being overworked is in question in this example
maybe the following would work where...when the data is inserted into
the database the changes are wrote to a file...then have the loop
that continuously checks that file for an update....thoughts?
I have table1 and i want to see if a specific row(based on a UID/key) has been updated since the last time i checked as well as continuously check for 60 seconds if the record bets updated...
I'm thinking i can do this using the INFORMATION_SCHEMA database.
This database contains information about tables, views, columns, etc.
attempt at a solution:
<?php
$timer = time() + (10);//add 60 seconds
$KEY=$_POST['KEY'];
$done=0;
if(isset($KEY)){
//loign stuff
require_once('Connections/check.php');
$mysqli = mysqli_connect($hostname_check, $username_check, $password_check,$database_check);
if (mysqli_connect_errno($mysqli))
{ echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
//end login
$query = "SELECT data1, data2
FROM station
WHERE client = $KEY
AND noted = 0;";
$update=" UPDATE station
SET noted=1
WHERE client = $KEY
AND noted = 0;";
while($done==0) {
$result = mysqli_query($mysqli, $query);
$update = mysqli_query($mysqli, $update);
$row_cnt = mysqli_num_rows($result);
if ($row_cnt > 0) {
$row = mysqli_fetch_array($result);
echo 'data1:'.$row['data1'].'/';
echo 'data2:'.$row['data2'].'/';
print $row[0];
$done=1;
}
else {
$current = time();
if($timer > $current){ $done=0; sleep(1); } //so if I haven't had a result update i want to loop back an check again for 60seconds
else { $done=1; echo 'done:nochange';}//60seconds pass end loop
}}
mysqli_close($mysqli);
echo 'time:'.time();
}
else {echo 'error:nokey';}
?>
Is this an adequate method and suggestions to improve the speed as well as improve the reliability
If I understand your application correctly, your client is a microcontroller. It issues an HTTP request to your php / mysql web app once in a while. The frequency of that request is up to the microcontroller, but but seems to be once a minute or so.
The request basically asks, "dude, got anything new for me?"
Your web app needs to send the answer, "not now" or "here's what I have."
Another part of your app is providing the information in question. And it's doing so asynchronously with your microcontroller (that is, whenever it wants to).
To make the microcontroller query efficient is your present objective.
(Note, if I have any of these assumptions wrong, please correct me.)
Your table will need a last_update column, a which_microcontroller column or the equivalent, and a notified column. Just for grins, let's also put in value1 and value2 columns. You haven't told us what kind of data you're keeping in the table.
Your software which updates the table needs to do this:
UPDATE theTable
SET notified=0, last_update = now(),
value1=?data,
value2?=data
WHERE which_microcontroller = ?microid
It can do this as often as it needs to. The new data values replace and overwrite the old ones.
Your software which handles the microcontroller request needs to do this sequence of queries:
START TRANSACTION;
SELECT value1, value2
FROM theTable
WHERE notified = 0
AND microcontroller_id = ?microid
FOR UPDATE;
UPDATE theTable
SET notified=1
WHERE microcontroller_id = ?microid;
COMMIT;
This will retrieve the latest value1 and value2 items (your application's data, whatever it is) from the database, if it has been updated since last queried. Your php program which handles that request from the microcontroller can respond with that data.
If the SELECT statement returns no rows, your php code responds to the microcontroller with "no changes."
This all assumes microcontroller_id is a unique key. If it isn't, you can still do this, but it's a little more complicated.
Notice we didn't use last_update in this example. We just used the notified flag.
If you want to wait until sixty seconds after the last update, it's possible to do that. That is, if you want to wait until value1 and value2 stop changing, you could do this instead.
START TRANSACTION;
SELECT value1, value2
FROM theTable
WHERE notified = 0
AND last_update <= NOW() - INTERVAL 60 SECOND
AND microcontroller_id = ?microid
FOR UPDATE;
UPDATE theTable
SET notified=1
WHERE microcontroller_id = ?microid;
COMMIT;
For these queries to be efficient, you'll need this index:
(microcontroller_id, notified, last_update)
In this design, you don't need to have your PHP code poll the database in a loop. Rather, you query the database when your microcontroller checks in for an update/
If all table1 changes are handled by PHP, then there's no reason to poll the database. Add the logic you need at the PHP level when you're updating table1.
For example (assuming OOP):
public function update() {
if ($row->modified > (time() - 60)) {
// perform code for modified in last 60 seconds
}
// run mysql queries
}
I have an application written in CakePHP version 1.2 and it was very slow because of the heavy and unoptimized queries to the database, this is an example of a deleas:
$pedidos_entregas = $this->Pedido->query('select pedidos.*, lojas.*, pessoas.*, formas_pagamentos.* from pedidos inner join veiculos_periodos
on pedidos.veiculos_periodo_id = veiculos_periodos.id inner join lojas
on veiculos_periodos.loja_id = lojas.id inner join pessoas
on pessoas.id = pedidos.pessoa_id inner join formas_pagamentos
on pedidos.formas_pagamento_id = formas_pagamentos.id
where
(finalizado = 1 or pedidos.id in
(
select pedido_id from status_pedidos where statu_id = 11
)
) order by entrega desc limit 200;');
Cache applied 30 minutes and much improved site performance. But when, after 30 minutes, one of the user will have to view the page slowly, to fill the cache again.
I captured the remaining time to finish each cache access controller that contains the use of the Cache.
$vencimento = file_get_contents(CACHE . 'cake_siv_financeiro_pedidos_entregas');
$vencimento = explode("\n", $vencimento);
$vencimento = $vencimento[0];
$agora = strtotime('now');
$faltam = ($vencimento - $agora)/60; //remaining time
echo $faltam;
For that, the win before the Cache 30 minutes, when missing 10 minutes or less, for example, if someone accesses the page, the cache already be updated again.
But still, a user will have to view the page slowly, because the query has to be done.
My question is: how to perform some function after the rendering of the view for the user? I want to do something like this, but this do not work
public function afterFilter()
{
parent::afterFilter();
//$this->atualizar_log();
$saida = $this->output;
$this->output = "";
ob_start();
print $saida;
flush();
ob_end_flush();
//I need that sleep after html returned to browser
sleep(500);
}
I have a second question, say I have a table sequinte:
table people
id (PK) name age
1 bob 20
2 ana 19
3 maria 50
and I run the following sql
UPDATE people SET age = 20 where id <3
This will affect the ID lines 1 and 2.
How, in CakePHP, after the update, grab the ids affected? (1 and 2)???
This is necessary when I delete existing caches;
It's not possible to execute code after a request. The best approach is to set up a cron job. You'll want to hook up a Cake Shell to cron - see http://book.cakephp.org/1.2/view/846/Running-Shells-as-cronjobs
If you can't use cron for whatever reason, consider having your clients fire an AJAX request to an action which updates the cache. This will happen after page load so there won't be a delay for the user.
edit: linked to 1.2 version of docs
to second question:
don't know if there is CakePHP way to do it but, you can still use mysql statement in query() method:
$sql = "SET #affids := '';
UPDATE people
SET age = 20
WHERE id < 3
AND ( SELECT #affids := CONCAT_WS(',', #affids, id) );
SELECT TRIM(LEADING ',' FROM #affids) AS affected; ";
$rs = $this->MODELNAME->query($sql);
debug($rs);
the query returns comma separated ids affected by the update.
i use my own mvc framework.
and post action is :
function post($pid = 0 , $title = '')
{
$pid = $this->input->clean($pid);
$stm =$this->Post->query("UPDATE posts SET `show_count`=show_count+1 WHERE id = $pid");
$stm->execute();
$row = $this->Post->find()->where(array('id'=>$pid))->fetchOne();
$this->layout->set('comments' , $this->comments($pid));
$this->layout->set('row' , $row);
$this->side();
$this->layout->view('post');
echo $this->layout->render($row['title']);
}
i want to when a record fetch from database plus one show_count column .
i use this query :
UPDATE posts SET show_count = show_count + 1 WHERE id = $pid
this right in localhost but in my shared host when run query instead of one pluses ,2 plus show_count column.
how can i solve this problem?
It's working in your localhost but not your internet host. The host is probably doing something behind the scenes that makes it not work. Also, since you don't have access to all the configuration stuff on the host server, you probably won't be able to just fix it.
Simplest fix is to do it in the software layer (assuming $pid is unique).
First get the show_count.
Then:
$oldShowCount = the current show_count
$newShowCount = $oldShowCount + 1
UPDATE posts SET show_count = $newShowCount WHERE id = $pid AND show_count = $oldShowCount
At this point, if no race conditions occurred the row will update (rows update = 1). If a race condition occurred, the update will fail (rows updated = 0).
Then check the # rows updated to verify it worked and repeat until it does.
This is quite common case.
You are running your script twice. Probably because browser is calling it twice. Check your rewrite rules.