PHP: mysqli clearing stored results - php

I was using this function to clear stored results after calling a procedure etc.
function clearStoredResults($mysqli_link){
#------------------------------------------
while($mysqli_link->next_result()){
if($l_result = $mysqli_link->store_result()){
$l_result->free();
}
}
}
But I keep getting the following message/error
mysqli::next_result(): There is no next result set. Please, call
mysqli_more_results()/mysqli::more_results() to check whether to call
this function/method in
If I change next_result() to more_results() the page keeps loading for a while and I get a time out error:
Maximum execution time of 30 seconds exceeded
any ideas on how to fix this?

You need to use both methods:
function clearStoredResults($mysqli_link) {
#------------------------------------------
while($mysqli_link->more_results()) {
$mysqli_link->next_result();
if($l_result = $mysqli_link->store_result()) {
$l_result->free();
}
}
}
Use more_results to control the loop, and next_result to actually move the cursor.

Related

PHP linear processing - script is waiting for an object to finish before proceeding

This may be a noob question, please consider the following script which in a nutshell corresponds to my real code:
---------------- class -------------
<?php
class BaseClass {
public $flag;
function __construct() {
$this->flag = 0;
}
function mainMethod() {
sleep(3);
$this->flag = 1;
}
function getFlag() {
return $this->flag;
}
}
?>
--------------- creating new instance -------------
<?php
require_once('test_class.php');
$test = new BaseClass;
$test -> mainMethod();
while($test -> getFlag() != 1) {
usleep(1000000); // 1sec.
echo "waiting";
}
?>
When the above class is instantiated, the $flag is set to 0 by constructor. Then the mainMethod() is called which sleeps for 3sec. and then sets the $flag to 1. The procedural "while" loop below checks for the $flag value. Ideally it should return the string "waiting" 3 times before it would allow the script to finish but it doesn't. The code is executed linearly and the "while" loop will never execute before the mainMethod() finishes its sleep time (hence never echoes "waiting").
Perhaps thought I could use the pcntl_fork() to split the call into 2 different processes but this code runs on Win 2008. Is there an easy way to make the "while" loop work (asynchronously) while the mainMethod() is being processed ?
Thank you.
Assuming this is for consumption in a webserver/browser, I recommend you redesign:
Run one request, that does the real work
via AJAX run the polling requests from the browser
couple those two via the session

How to do mysql_data_seek in CodeIgniter?

I'm trying to reset the pointer to the first record in CodeIgniter. Consider the following greatly simplified code:
$query_milestones = "SELECT * FROM milestones";
$milestones = $this->db->query($query_milestones);
foreach($milestones->result() as $milestoneRow){
// do something
}
$milestones->data_seek(0); // <--- This gives me Fatal error.
foreach($milestones->result() as $milestoneRow){
// do something else
}
This gives me:
Fatal error: Call to undefined method CI_DB_mysql_result::data_seek()
How can I do a mysql_data_seek with CodeIgniter?
UPDATE: It seems VERY odd to me but resetting the pointer apparently is not necessary. The following does what I want but not what I expect:
$query_milestones = "SELECT * FROM milestones";
$milestones = $this->db->query($query_milestones);
foreach($milestones->result() as $milestoneRow){
// do something
}
// As soon as the foreach is reached, the first record is retrieved again.
foreach($milestones->result() as $milestoneRow){
// do something else
}
try #$this->db->data_seek(0); instead of $milestones->data_seek(0);
You can try $milestones->_data_seek(0); but I have not used CodeIgniter in a while and supposedly it is a private method, at least it used to be.

PHP microtime strange behavior

I was looking at execution time of some functions, but i have found that microtime is getting wrong, in one microtime()
implementation №1 always first time is always getting more then second microtime() executing, when i testing one function and saw that one case is faster then another, but after place replace (2nd function to 1st place), it getting slower anyway, even if it was 3x faster...
function dotimes($times,$eval,$data=false) {for(;--$times;) eval($eval);}
$start = microtime(true);
dotimes(1000,'$i = $i?$times/2:1;');
printf(": executed : %f\n",microtime(true)-$start);
$start = microtime(true);
dotimes(1000,'$i = $i?$times/2:1;');
printf(": executed : %f\n",microtime(true)-$start);
// 1st case is always slower...
implementation №2 iv made sometimes before microtime() as static data storage, but in that case the time of execute is always second time is slower then first (oposite to implementation №1)
function get_execution_time()
{
static $microtime_start = null;
return $microtime_start === null ? $microtime_start = microtime(true) : microtime(true) - $microtime_start;
}
function dotimes($times,$eval,$data=false) {for(;--$times;) eval($eval);}
get_execution_time();
dotimes(1000,'$i = $i?$times/2:1;');
printf(": executed : %f\n<br>",get_execution_time());
get_execution_time();
dotimes(1000,'$i = $i?$times/2:1;');
printf(": executed : %f\n<br>",get_execution_time());
//now 2nd case is faster..
Can somebody tell me what is going up? Why these microtimes in one case 1st always slower, and throught static storage 2nd execute is slow down, WHY?
ps if someone need tiny mt function here is my FIXED AND WORKING CORRECT:
function get_mt() {static $mt; return $mt ? microtime(true)-$mt.$mt=null : $mt=microtime(true);}
attached :
function get_mt() {static $mt; return $mt?microtime(true)-$mt:$mt=microtime(true);}
function dotimes($times,$eval,$data=false) {for(;--$times;) eval($eval);}
$start = microtime(true);
get_mt();
dotimes(10000,'$i = $i?$times/2:1;');
printf(":clean executed : %f\n<br>",microtime(true)-$start);
printf(":static executed : %f\n<br>",get_mt());
$start = microtime(true);
get_mt();
dotimes(10000,'$i = $i?$times/2:1;');
printf(":clean executed : %f\n<br>",microtime(true)-$start);
printf(":static executed : %f\n<br>",get_mt());
So far, I see that implementation №1 is correct. No clue what you tried in your second implementation.
The advice here - never test two cases in the same script. Run them separately a few times and then find the average time. PHP allocates memory when it needs and this is a slow operation. The second case may reuse already allocated memory and skip this operation and you get wrong results.
static makes a variable semi global within that function retative to function name.
I would say the delay goes in the fact that the static array needs to be checked for the previous value of the static variable.
extra work == delay

PHP long poll fails

I have this loop to long poll:
$time = time(); //send a blank response after 15sec
while((time() - $time) < 15) {
$last_modif = filemtime("./logs.txt");
if($_SESSION['lasttime'] != $last_modif) {
$_SESSION['lasttime'] = $last_modif;
$logs = file_get_contents("./logs.txt");
print nl2br($logs);
ob_flush();
flush();
die();
}
usleep(10000);
}
problem is: the "if" condition is never entered in the middle of the while loop, even if logs.txt is modified. I have to wait 15sec till the next call to this file to obtain the updated content (so it becomes a regular, "setTimeout style" AJAX polling, not a long-poll). Any idea why ?
This is because of the filemtime() function : its results are cached. Thus each time your loop is executed the timestamp's the same for 15 seconds.
I have not tried it myself, but according to w3cschools :
The result of this function are cached. Use clearstatcache() to clear the cache.
Hope that helps !

Executing MySQL Queries and Creating Instances several Times within Loop

I have an Web Application that requires SELECT and INSERT Querying to MySQL database and Instantiating a PHP class using new operator almost more that thousand times within a loop. May be there are alternatives to my present logic, but my point is that is there any harm if I carry on this logic?. I don't bother about the time complexity associated with the algorithm presently but **worrying much about if anything goes wrong during transaction or memory usage. I am giving the piece of code for reference
$stm_const = "select ce.TIMETAKEN, qm.QMATTER as STRING1, ce.SMATTER as STRING2 from w_clkexam ce, clkmst cm, qsmst qm where ce.QID=qm.QID and cm.ROLLNO=ce.ROLLNO";
for ($c=0; $c < count($rollnos); $c++) {
$stm3 =$stm_const." "."and ce.ROLLNO='$rollnos[$c]'";
$qry3 = mysql_query($stm3) or die("ERROR 3:".mysql_error());
while($row1 = mysql_fetch_array($qry3)) {
echo $string1=$row1['STRING1'];
echo $string2=$row1['STRING2'];
$phpCompareStrings=new PhpCompareStrings($string2, $string1);
$percent=$phpCompareStrings->getSimilarityPercentage();
$percent2=$phpCompareStrings->getDifferencePercentage();
echo '$string1 and $string2 are '.$percent.'% similar and '.$percent2.'% differnt<br/>';
}// end while
}// end for
Please help, I am waiting for opinions from you so that I can move further. Thanks in advance.
I don't see any problem there. You just get all the rows from database and for each row compare the strings. As you assign the object to the same variable each time, the old object is destroyed before the new object is created. So you have only one instance of the object in memory at all times. The question is what you want to do with the results? Only print them as in your example, or to store the results for further processing?
Anyway, I think it is not possible to optimize your code without modifying the class. If you are using this class, you can try to modify it so that it can accept multiple strings. Using this, you can create only 1 instance of the class and you avoid destroying/creating the object for every row. It will save you some CPU time, but not memory (as at all times, only 1 instance of the class is active).
Untested modification below:
Modify this function inside the class:
function __construct($str1,$str2){
$str1=trim($str1);
$str2=trim($str2);
if($str1==""){ trigger_error("First parameter can not be left blank", E_USER_ERROR); }
elseif($str2==""){ trigger_error("Second parameter can not be left blank", E_USER_ERROR); }
else{
$this->str1=$str1;
$this->str2=$str2;
$this->arr1=explode(" ",$str1);
$this->arr2=explode(" ",$str2);
}
}
To these 2 functions:
function init($str1,$str2){
$str1=trim($str1);
$str2=trim($str2);
if($str1==""){ trigger_error("First parameter can not be left blank", E_USER_ERROR); }
elseif($str2==""){ trigger_error("Second parameter can not be left blank", E_USER_ERROR); }
else{
$this->str1=$str1;
$this->str2=$str2;
$this->arr1=explode(" ",$str1);
$this->arr2=explode(" ",$str2);
}
}
function __construct($str1,$str2){ $this->init($str1,$str2); }
Then create the object outside the loop and only call $phpCompareStrings->init($string2,$string1) inside the loop.

Categories