PHP + MySQL: File reading limit and connection error - php

I'm having problem with query caching in files. I have a code which is trying to get file with serialized query result and if file is not found, or older then one day then I'm trying to connect to DB and get it remotely. Code looks like this:
// Getting cache file function
$cur_time = #time();
$time_modified = #filemtime($file_path);
if ($cur_time > ($time_modified + $cache_period_hours))
return NULL;
else
return unserialize(file_get_contents($file_path));
//If NULL is returned get result remotely;
if($result === NULL){
if (!db::connect("base", "192.168.1.111", "root", "password"))
die("Database error. Can not connect to database.");
//Execute query, write to file serialized result
}
When I have huge traffic I get this error:
Lost connection to MySQL server at 'reading authorization packet', system error: 0.
But I don't know why the script is even trying to connect to database when I have fresh cached file. Is there a limit on how many users can read same file at same time? Also is there any way to prevent this MySQL error?

Change to:
if ($cur_time > ($time_modified + $cache_period_hours*3600))
This will convert $cache_period_hours to seconds, to match the units of the other variables.

Related

How to fix MySQL "Got an error reading communication packets" error

I have created some PHP code for my website to call a stored procedure in my database. This will get text from a table so that I can dynamically update the text on the web page without modifying it in code.
This part works very well so far. However, When I open the MySQL error log I see the following message printed:
Aborted connection 161 to db: 'dbname' user: 'username' host: 'localhost' (Got an error reading communication packets)
I have checked the firewall, which is inactive.
I have attempted using 127.0.0.1 instead of localhost in the PHP code.
I have cleared the results using "mysqli_free_result($result);", this did seem to remove one of the two errors I got per query.
I have checked the max allowed packet size, which is 16M.
I have un-commented the extension mysqli in the php.ini file.
PHP:
<?php
$servername = "localhost";
$username = "username";
$password = "password ";
$dbname = "dbname";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "Call StoredProcedure('primarykey',#OutValue);";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo $row["ColumnHeader"];
}
} else {
echo "0 results";
}
mysqli_free_result($result);
$t_id = mysqli_thread_id($conn);
mysqli_kill($conn,$t_id);
mysqli_close($conn);
?>
SQL:
CREATE DEFINER=`username`#`hostname` PROCEDURE `StoredProcedure`(IN PrimaryKey
VARCHAR(50), OUT Result VARCHAR(50))
BEGIN
start transaction;
select ColumnName
from dbname.tablename
where PrimaryKeyColumn = PrimaryKey;
commit;
END
As I mentioned, I am getting the expected result from my query and it is perfectly functional, so I am not sure what can be the cause.
The server is running MySQL version 5.7.27-0ubuntu0.18.04.1((ubuntu)). Any help with this would be greatly appreciated!
Update - 11/Sep/2019:
I have attempted to check how long the execution of the my PHP script takes. To do this I added the following code borrowed from this thread:
Tracking the script execution time in PHP.
// Script start
$rustart = getrusage();
// Code ...
// Script end
function rutime($ru, $rus, $index) {
return ($ru["ru_$index.tv_sec"]*1000 + intval($ru["ru_$index.tv_usec"]/1000))
- ($rus["ru_$index.tv_sec"]*1000 + intval($rus["ru_$index.tv_usec"]/1000));
}
$ru = getrusage();
echo "This process used " . rutime($ru, $rustart, "utime") .
" ms for its computations\n";
echo "It spent " . rutime($ru, $rustart, "stime") .
" ms in system calls\n";
However, the result was the following:
This process used 0 ms for its computations It spent 1 ms in system calls
Which should not cause any timeouts.
I also activated the general log file on the server and i did see that the it would track the query as follows:
Command Type, Detail
Connect, username#hostname on dbname using Socket
Query, Call StoredProcedure('PrimaryKey', #result)
I am curious about there being no log saying disconnect though I do not know if this is default behaviour from MySQL.
Another curious thing I discovered was that MySQL Workbench states my query time for the stored procedure is on average 7ms but all resources I could find states that PHP waits for the query to finish before continuing.
Query, Total Time, Max Time, Avg Time
CALL StoredProcedure ( username # hostname ) , 98.94, 66.26, 7.07
In short, I still have not found any solutions to the issue, but potentially some leads that could eventually lead to a resolution.
Update - 18/Sep/2019:
After more digging on the issue I've come across the following thread:
https://dba.stackexchange.com/questions/144773/mysql-aborted-connection-got-an-error-reading-communication-packets
It is suggesting that due to MySQL and PHP being installed on the same server, they are competing for RAM. Considering my server is running on a Raspberry Pi 3 model B, this seems like a plausible explanation for the issue I am facing.

Call to a member function fetch_assoc() on a non-object on linux server but not on windows

I am getting the above error when I run this page on a linux server, but it doesn't give me any errors when running it on a windows machine.
The following is my script:
include_once '/../src/init.php';
$userid = $user_data['userid'];
$date = ('Y-m-d'); //get todays date from the server
$db = new mysqli('localhost', 'root', '', 'logfile');
if ($db->connect_error) {
$error = $db->connect_error;
} else {
$sql = "SELECT a.kiloLogid,a.travelDate,a.openning, a.closing, a.clientsName,a.timeIn,a.timeOut, a.destination,a.diff
FROM viewDailyDiff a
WHERE a.`userid` = $userid AND a.`travelDate` = '".$date."'";
$result = $db->query($sql);
if ($db->error) {
$error = $db->error;
}
}
function getRow($result)
{
return $result->fetch_assoc(); //the error is on this line
}
Please assist
I thing the included file init.php
should have the call for the getRow function.
and when there is a problem with Linux to Windows change there are most chances to find solution with .htaccess. Try not to download the .htaccess
All the best
Usually when this happens to me, it's because there is no data returned. If the "work/fail" change is moving to a new server, often this is because the new server has no permission to get the data. So no results are returned. Even thought the original server with the same select statement had records returned, avoiding the error.
If no results are returned, calling fetch_assoc on an empty data set will toss an error in more recent php. So the version of php from one server to the next can also be a factor.
Put in code to only call fetch_assoc if there are records returned (never a bad idea) and/or try to run the command manually (command line?) using mysql client from the command prompt to verify permissions and data. Often the ClI will be more verbose with the error results.

Using PHP to connect to MS Access DB using ODBC keeps on locking

I know this is not the best setup, but I'm stuck with it and cannot change it.
PHP connects to a local MS Access DB (.mdb) to log certain activities being done by the script. This works fine when only one instance of the script is running. However, if run two instances, I occasionally get the following error:
odbc_exec(): SQL error: [Microsoft][ODBC Microsoft Access Driver] Could not update; currently locked., SQL state S1000 in SQLExecDirect
This only happens intermittently so I'm assuming it's only when the two scripts both happen to be trying to write to the same table at the same time. I never had this issue with other DBs such as MySQL. How can I tell PHP/ODBC/Access to either not lock or try again if it is locked?
I also usually have the Access DB open on my screen for troubleshooting purposes.
odbc_exec() returns FALSE if the query fails, so you could just check the result of the query and keep trying until it succeeds:
$sql = "UPDATE [Clients] SET [Position]='somewhere' WHERE [ID]=1";
while (TRUE) {
$result = odbc_exec($conn, $sql);
if ($result) {
break;
}
else {
$lastError = odbc_error();
if ($lastError != "S1000") {
echo "ODBC error $lastError";
break;
}
}
sleep(1);
}

SQL query err_empty_response

I have a problem when executing a simple piece of code:
$con=mysqli_connect($host,$user,$password,$database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM exercises");
if (mysql_num_rows($result) > 0) {
}
The variables on the first line are imported from another file. Everything works until I try to do anything with the $result variable. I can get the result from the database without an error, but as soon as I start doing something with it in an if statement or a loop (to fetch the results), my page will simply not load, and I get an err_empty_response. I tested it in multiple browsers. Also, some other of these issues on stackoverflow did not seem to have the soultion to the problem.
All help is appreciated.

mysql server has gone away in result of storing API response in php

i am experiencing mysql server has gone away in response of storing API result in mysql database through php code is follow,
$api_response = sendmsg($group_detail['cell_no'], $SMS); //function to execute API
//update sms sent record
$sql = "INSERT INTO sms_sent_record (record_id, api_response)
VALUES (NULL, '$api_response')";
$result = mysql_query($sql) or die('Error, updating sms & group count
in sms_sent_count failed : ' . mysql_error());
i have tried many other options such as storing api response in array and then store it in mysql table, but in any way it throws the same error. The other code in function after this error will not executed by server.
i think it is due to delay in api response and timeout problem in mysql.
Is there any way to avoid this error and storing result in proper way.
Does it work if you omit the sendmsg and do:
$api_response = 'test';//sendmsg($group_detail['cell_no'], $SMS); //function to execute API
If so, does sendmsg() use some sort of mysql connection at any time?
If it does, you may want to store the link from when you connected to the database the first time and reuse it.
$link=mysql_connect();
..
..
mysql_query($sql,$link);
There are lots of reasons for the gone away message but I suspect your problem is that you open the connection to your DB before the API call (to send an SMS ?) and the API call causes the server to terminal your connection before the INSERT is run
Try moving your open db connection to just before the INSERT statement :
$api_response = sendmsg($group_detail['cell_no'], $SMS); //function to execute API
// open connection here
$sql = "INSERT INTO sms_sent_record (record_id, api_response)
VALUES (NULL, '$api_response')";
$result = mysql_query($sql) or die('Error, updating sms & group count
in sms_sent_count failed : ' . mysql_error());
Check your value set for wait_timeout this is
The number of seconds the server waits for activity on a
noninteractive connection before closing it.
If you have this value set very low the server will timeout your connection between opening your connection and running your query.

Categories