There is useful method getStats in Db-component Yii
$sql_stats = YII::app()->db->getStats();
echo $sql_stats[0] //the number of SQL statements executed
echo $sql_stats[1] //total time spent
Official documentation link
Is there method in Yii2 to get this information?
Here is equivalent for Yii 2:
$profiling = Yii::getLogger()->getDbProfiling();
$profiling[0] contains total count of DB queries, $profiling[1] - total execution time.
Note that if you want to get information about all queries at the end of request you should execute this code in right place, for example in afterAction():
public function afterAction($action, $result)
{
$result = parent::afterAction($action, $result);
$profiling = Yii::getLogger()->getDbProfiling();
...
return $result;
}
Otherwise you will get the information according to the moment of execution this command.
Official documentation:
getDbProfiling()
afterAction()
If you enable the debugging toolbar you get a lot more info, it is much much better than this. Also you can enable logging that should also get you much more info.
More info on the debugging toolbar here http://www.yiiframework.com/doc-2.0/ext-debug-index.html and more info about the logging here http://www.yiiframework.com/doc-2.0/guide-runtime-logging.html
Related
I've been spent hours trying to figure out how I'm supposed to get around this error in my scenario. I'm trying to run a few queries in sequence.
I have read: codeigniter : Commands out of sync; you can't run this command now, however I am not able to update /system/database/drivers/mysqli/mysqli_result.php
I've tried:
$this->db->reset_query();
$this->db->close();
$this->db->initialize();
$this->db->reconnect();
mysqli_next_result( $this->db->conn_id );
$query->free_result();
But they either give me the same error, or different errors which I will detail in the comments of my code.
The way my code is organized- I have a make_query method that takes a bunch of search options and figures out which tables to join and fields to search based on those. Sometimes, I just want to count results, sometimes I want all of the resulting data, sometimes I just want distinct values for certain fields or to group by certain fields. So I call make_query with my options, and then decide what to select afterwards. I have also been saving my query text to report, so that users can see what query is being run.
One interesting thing I have noted is that when I have no options set (ie there are no WHERE clauses in my SQL), I do not get this error and the multiple queries are able to run with no problem!
Here is my code:
//Get rows from tblPlots based on criteria set in options array
public function get_plot_data($options=array()){
$this->db->save_queries = TRUE;
log_message('debug','before make query 1 get plot data');
$this->make_query($options,'plot');
log_message('debug','after make query 1 get plot data');
$this->db->distinct();
//Now, set select to return only requested fields
if (!empty($options['fields']) and $options['fields']!="all" ){
//Because other tables could be joined, add table name to each select
array_walk($options['fields'], function(&$value, $key) { $value = 'tblPlots.'.$value;} );
$this->db->select($options['fields']);
}
if (!empty($options['limit']) and $options['limit']>0){
$this->db->limit($options['limit'], $options['offset']);
}
//Get the resulting data
$result=$this->db->get('tblProgram')->result();
$query_text = $this->db->last_query(); //tried removing this but didn't help
log_message('debug','query text '.$query_text);
$this->db->save_queries = FALSE;
//get the number of rows
//$this->db->reset_query();
//$this->db->close();
//$this->db->initialize();
//$this->db->reconnect();
//mysqli_next_result( $this->db->conn_id );
//$this->db->free_result(); //Call to undefined method CI_DB_mysqli_driver::free_result()
//$result->free_result(); //Call to a member function free_result() on array
log_message('debug','before make query 2');
$this->make_query($options,"plot");
$this->db->select('pkProgramID');
log_message('debug','before count results');
//this is where my code errors out trying to do the next step:
$count=$this->db->count_all_results('tblProgram');
}
I'm not including the code for make_query because it is long and calls other functions, but it runs successfully the first time and outputs the SQL query I would expect. If it would be helpful, I can include that code as well.
I'm not sure how to correctly call free_result() given that the CI documentation only gives an example using query('SQL QUERY') and I am building the query using Active Record, so I'm not sure how to use free result in my scenario? Maybe that's the issue?
$query2 = $this->db->query('SELECT name FROM some_table');
$query2->free_result();
Thank you for any help!
I ended up posting on a CI forum that suggested https://www.youtube.com/watch?v=yPiBhg6r5B0 which worked! Also I ended up having to join my tables differently to avoid timeouts (I think I was having trouble because I was using AJAX to call many queries asynchronously and one of them was timing out). Hope this helps someone!
I am trying to get a reply text message from Clickatell using their Rest API, when I call the parseReplyCallback function when their system posts to my page - it seems to be null or I am not sure how to get the variables it is returning. What I would like to do is have all of the variables returned insert into a SQL database so I can use it elsewhere.
I have tried quite a few things, using various styles of getting the variables such as $_POST, $results['text'], $results->text, and so forth each time I can't seem to get any information out of it. I can't just var_dump or anything because I can't see any backend or console so I am pretty much in the blind, hoping someone else is using this system and has it working fine.
require __DIR__.'/clickatell/src/Rest.php';
use clickatell\ClickatellException;
use clickatell\Rest;
$Rest = new Rest("j8VKw3sJTZuVfQGVC7jdhA");
// Incoming traffic callbacks (MO/Two Way callbacks)
$Rest->parseReplyCallback(function ($result) {
//mysqli_query($con,"INSERT INTO `SMSCHAT` (`text`) VALUES ('$result')");
$mesageId = mysqli_real_escape_string($con,$result['messageId']);
$text = mysqli_real_escape_string($con,$result['text']);
$replyMessageId = mysqli_real_escape_string($con,$result['replyMessageId']);
$to = mysqli_real_escape_string($con,$result['toNumber']);
$from = mysqli_real_escape_string($con,$result['fromNumber']);
$charset = mysqli_real_escape_string($con,$result['charset']);
$udh = mysqli_real_escape_string($con,$result['udh']);
$network = mysqli_real_escape_string($con,$result['network']);
$keyword = mysqli_real_escape_string($con,$result['keyword']);
$timestamp = mysqli_real_escape_string($con,$result['timestamp']);
//do mysqli_query
});
I'd like for it to break the result into individual variables (because I plan on doing other things such as an auto-reply, etc) and upload it to the SQL database scrubbed.
Either doesn't create the table entry or gives me a blank one altogether in that first test where I put the result in the text field.
From a Clickatell point of view, although we understand what you're asking - it's unfortunately outside the scope of support that we offer on our products.
If you would like more information on our REST API functionality, please feel free to find it here: https://www.clickatell.com/developers/api-documentation/rest-api-reply-callback/
If you don't succeed in setting up the callbacks, please feel free to log a support ticket here: https://www.clickatell.com/contact/contact-support/ and one of our team members will reach out and try to assist where possible.
I've been searching for a suitable PHP caching method for MSSQL results.
Most of the examples I can find suggest storing the results in an array, which would then get included to page. This seems great unless a request for the content was made at the same time as it being updated/rebuilt.
I was hoping to find something similar to ASP's application level variables, but far as I'm aware, PHP doesn't offer this functionality?
The problem I'm facing is I need to perform 6 queries on page to populate dropdown boxes. This happens on the vast majority of pages. It's also not an option to combine the queries. The cached data will also need to be rebuilt sporadically, when the system changes. This could be once a day, once a week or a month. Any advice will be greatly received, thanks!
You can use Redis server and phpredis PHP extension to cache results fetched from database:
$redis = new Redis();
$redis->connect('/tmp/redis.sock');
$sql = "SELECT something FROM sometable WHERE condition";
$sql_hash = md5($sql);
$redis_key = "dbcache:${sql_hash}";
$ttl = 3600; // values expire in 1 hour
if ($result = $redis->get($redis_key)) {
$result = json_decode($result, true);
} else {
$result = Db::fetchArray($sql);
$redis->setex($redis_key, $ttl, json_encode($result));
}
(Error checks skipped for clarity)
From my studies I understand that one should free the result set data, after manipulating/using the Query data. I am trying to use the mysqli_result::free pdo in the following code context:
if ($result)
{ $change = $result[0][9];
$change = $change+1;
$sql='UPDATE users SET visits = :visit WHERE username = :username';
$q=$dbh->prepare($sql);
$q->bindValue(':username',$username,PDO::PARAM_STR);
$q->bindValue(':visit',$change,PDO::PARAM_INT);
$q->execute();
// initiate SESSION and Set USER SESSION Variables through the --session_handler.php
require ('./includes/session_handler.php');
//Free the Query Result set to free memory on the database handler
$result->free();
// direct registered users to MEMBER_ZONE.php for registered users interface
header('Location: member_zone.php');
exit();
}
I receive the message :
Fatal error: Call to undefined method PDOStatement::free() in...
I have researched at http://php.net/manual/en/mysqli-result.free.php as well as on Google and found no example code to further elucidate its application.
On this site the examples : mysqli_result::free increase php memory usage
Here it is confusing: shouldn't in this code the $row be freed?
And here Are mysqli_result::free and mysqli_stmt::free_result the same?
Here two forms of free_result() and free() are used together.
I cannot seem to find my error or a clear usage example. I would appreciate any input.
It seems I was using the $q->free() on a result, which never came, because I was updating the database, not requesting a result. The syntax seemed to be correctly used. It was my order of use which I think was wrong.
I'm testing performance on a CMS I'm making, and I'm wondering is it possible to view what queries were ran on a page load. For example, let's say I run 'test.php'. When I go to it, a list of queries ran by mySQL show at the bottom of the page - is this possible? I've seen sites do this before.
Thanks
The function SHOW FULL PROCESSLIST will show the real-time and past history of all processes.
SHOW FULL PROCESSLIST
If you are using a server on which you have the rights to install packages, you can install mysqltop and test in real time file and MySQL resource usage and queries.
Well, if all your queries go through a function then it should be easy, but if each only uses the standard call, then it won't be. This also let's you switch to a different database type or something like that easily.
For instance on the CMS's I modified to be a library program, I have a DB Query function:
function db_query($qstring, $conn) {
$dbh = mysql_db_query($dbname,$qstring, $conn);
// this is where I would add some incrementing code, but it has to be global.
// or just do something like
if($_GET["debug"]=="debuginSQLcount"){
echo $qstring
}
return $dbh;
}
then to use it, I just do something like
$sql = "SELECT stuff";
}
$result = db_query($sql, $link);
if (!$result || db_numrows($result) < 1) {
If you do it like this, then just add a line to the function which increments a $GLOBALS variable or something like that. Read more at PHP global or $GLOBALS