Wordpress - Close connection in php script - php

I am implementing a script in php for a Wordpress blog. The script should be executed every five minutes. The script opens a mysql connection and I want to close it when I am finished. Can you check if it works?
$db = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
mysql_select_db("XY", $db);
//set data into $data
foreach ($data => $info) {
//do stuff inserts
}
mysql_close();
Is the approach right? I am closing the connection used in this script or I am closing also other connections?

Closing the connection explicitly is not mandatory. PHP cleans up all the resources when the script finishes, this includes database connections or sockets, filehandles, any internal resources like images and last but not least, memory blocks.

You could pass your $db variable to the mysql_close() function call. Like mysql_close($db).
But be aware that the mysql_* are deprecated and will be removed in a future php version. You should look into the mysqli_* functions instead.

Related

"MySQL server has gone away" when running script as cronjob

I have a cronjob running a PHP script that fetches a few hundred RSS feeds, parses them, updates a database, and then writes new Atom and RSS feed files.
The script runs fine when I call it in the browser, but when I let crond run it, it mails me the following error:
Warning: mysqli::query(): MySQL server has gone away in /script.php on line 149
Here is the relevant section of code from the script:
// ...
// the script has now been running for some time,
// fetching feeds, parsing them, and updating the database;
// now we check if the connection to the mysql server is still there,
// and then query the database and write the feed files
if (!isset($mysqli)) {
$mysqli = new mysqli($db_host,
$db_username,
$db_password,
$db_name);
$mysqli->set_charset('utf8');
$mysqli->query("SET lc_time_names = 'de_DE'");
}
$query = "..."; // some SELECT query
if (!($result = $mysqli->query($query))) { // this is line 149
// error message
}
// write the feed files
// ...
As you can see, I check, if the connection stands, before I send the query. Apparently, the database server drops the connection between checking it and performing the query. At least that is what I guess.
So, why is this happening, and what can I do to keep the connection alive (if that is actually the problem)?
My PHP scripts run on a shared server (Linux with Apache), and I don't have root access to the MySQL server – so none of the related questions answer my problem, since they all recommend to change settings in the database server config files.
Also, if called from the browser, the script is run under a different PHP version (5.6) than when I have crond execute it (5.5). See this related question.
I have tried closing the existing connection and reestablishing it, as recommended in this answer:
$mysqli->close();
if (!isset($mysqli)) {
$mysqli = new mysqli($db_host,
$db_benutzername,
$db_passwort,
$db_name);
$mysqli->set_charset('utf8');
$mysqli->query("SET lc_time_names = 'de_DE'");
}
and I have tried to set the execution time limit, as recommended in this answer:
set_time_limit(180);
or in Prince Rajput's answer below:
ignore_user_abort(true);
set_time_limit(0);
but none of that helped.
Try this on the header of cron job file:
<?php
ignore_user_abort(true);
set_time_limit(0);
?>
The problem with the first attempt at a solution (given in my question) is that closing a connection does not unset the variable, so that in
$mysqli->close();
if (!isset($mysqli)) {
the if-condition is always false.
One solution would be to unset the variable after closing the connection:
$mysqli->close();
unset($mysqli);
if (!isset($mysqli)) {
but a simpler solution is to check the connection instead of the variable:
if (!mysql_ping($mysqli)) {
(Note that of course we do not close the connection to test if it is open.)

PDO MySQL Connection close - unset vs null

I've read in PDO manual that to close connection you should use the following:
$connection = null;
However, Some people suggested that since PHP 5.3 has a new GC, the following should be used:
unset($connection);
I need to know once and for all, which one is preferred, or are they the same?
They do the same thing. Unsetting the $pdo handle and setting it null both close the connection.
You can test this for yourself. Run the following script in one window, and in a second window open the MySQL client and run SHOW PROCESSLIST every couple of seconds to see when the connection disappears.
<?php
$pdo = new PDO(..);
sleep(10);
unset($pdo);
echo "pdo unset!\n";
sleep(10);
Then change unset($pdo) to $pdo=null; and run the test again.
<?php
$pdo = new PDO(..);
sleep(10);
$pdo = null;
echo "pdo set null!\n";
sleep(10);
The extra sleep() at the end is there to give you a moment to see that the connection has dropped, before the PHP script terminates (which would drop the connection anyway).
I stumbled with this. I have a PDO object that spans setup and teardown, and I can't find where there must be a remaining reference, as setting $pdo to null did not resolve the problem.
User Contributed Notes in http://php.net/manual/en/pdo.connections.php discusses the problem of delayed closure. Here they suggest killing the current connection:
$pdo->query('SELECT pg_terminate_backend(pg_backend_pid());');
$pdo = null;
This is for postgres. For mysql I have used:
$pdo->query('KILL CONNECTION CONNECTION_ID();');
using
$pdo = null; //is an assignment to null; the variable still declared in the memory.
but
unset($pdo); // will call the function to distroy also the adress "#" pointed by the variable.
so using unset is prefered.
Just don't bother with closing at all. PHP will close it for you all right.
Note that of course your application have to be sanely designed, without the need of reconnecting to different databases at a rate of machine-gun. And even in latter case, the method you are using to close would be the least problem. You are barking wrongest tree ever. Work the number of connections, not the way you are closing them.

is mysql_connect in header bad practice?

I have a normal website. It uses PHP to call a MySQL table. To save on typing it out all the time, I include() a connect.php file which connects to the database for me on every page. The website keeps getting a "mysql too many connections" error. Is it a bad idea to connect at the start of a page like this?
Should I create a new connection each time a PHP script needs it, then close that connection with mysql_close after that script is done? I had avoided doing as it would add repeated lines of code to the website but I'm wondering if that's what's causing the issue?
So at the moment my code is similar to this:
<?php
include("connect.php"); //connects to database using mysql_connect() function
...
PHP script that calls mysql
...
another PHP script that calls mysql
?>
Should I change it to something like this?
<?php
mysql_connect('host', 'username', 'password');
mysql_select_db('db');
PHP code that calls mysql
mysql_close();
...
mysql_connect('host', 'username', 'password');
mysql_select_db('db');
more PHP code that calls mysql
mysql_close();
?>
You should avoid making new connections to your database, as long as possible.
Making connection to database is a slow and expensive process. Having an opened connection consume few resources.
By the way, stop using mysql_* functions. Use mysqli_* or PDO.
Should I create a new connection each time a PHP script needs it [...] ?
Yes, that makes most sense, especially if not every page needs a mysql connection.
In PHP this works by setting up the database credentials in the php.ini file and you can just call mysql_select_db and it will automatically connect to the configured database if no connection exists so far.
If you write new code, encapsulate the database connection in an object of it's own so that you can more fine-grained control when to connect to the database.
Modern frameworks like for example Silex allow you to lazy load such central components (Services), so you have configured them and can make use of them when you need them but you don't need to worry about the resources (like the connection limit in your example).
[...] close that connection with mysql_close after that script is done?
You don't need that normally because PHP does this for you.
I do not think there is anything really wrong with this style of coding. It all depends on what kind of app you are writing. Just make sure you check your scripts well and get ride of any errors, you should be fine.
This is what i usually do
<?php session_start(); include "inc/config.php";
//require_once('chartz/lib/idiorm.php');
if ($_SESSION["login1"]== "Superadmin" or $_SESSION["login1"]== "User" or $_SESSION["login1"]=="Administrator")
{
$snames = $_SESSION["name1"];
$id = $_SESSION["id1"];
$stype = $_SESSION["login1"];
$stokperm = $_SESSION['stokperm'];
$navtype = $_GET['nav'];
include("inc/ps_pagination.php");
}
else
{
header ("location: ../../../index.php");
}
?>
Am not saying its the very best way out there, we are all still learnig...
I also thing you should take the advice of blue112 very seriously. Most of my apps are writing in the old fashion way, but Use mysqli_* or PDO is the way to go.

Using same MySQL Connection in different PHP pages

I am creating a simple Web Application in PHP for my college project. I am using the MySQL database.
I connect to the database in login.php. After connection I assign the connection to $_SESSION["conn"] and then redirect to main.php.
In main.php I write $conn = $_SESSION["conn"]. But the connection in $conn does not work.
I thought that as the login.php script ends, the connection gets closed. So I tried using mysql_pconnect instead of mysql_connect but that too does not work.
I know I can reconnect to the database in every PHP file. But I don't want to do this. I want to use the same connection in all PHP files.
Instead of saving the DB connection in a session you should make the connection calls in a separate file such as db.php and then require it from each of your scripts. For example, place your connection in db.php:
mysql_connect('...', '...', '...');
mysql_select_db('...');
and then bring it in in login.php:
require('db.php');
$res = mysql_query('...');
You can then do the same for each PHP file that needs access to the DB and you'll only ever have to change your DB access credentials in one file.
After connection I assign the connection to $_SESSION["conn"] and then redirect to main.php.
You'll probably want to read up on PHP sessions. You can't store resources (database connections, file handles, etc) in a session, because they can not be serialized and stored.
Keep in mind that each and every visit to a PHP script invokes a new instance of the PHP interpreter (via CGI, via FastCGI, or via a built-in module), and invokes a new instance of the script. Nothing is shared between script calls, because the entire environment goes away when the script exits.
The other answers are correct -- you'll need to connect to the database on every script call. Place the connection in a common include file for convenience.
The second request may not be served by the same web server process as the first, which means that you will have a completely separate set of database resources. You'll need to connect again in this new process in order to run queries.
What I normally have is a Connection class that pages will require in order to establish a connection. Something along the lines of:
class Connection {
public $dbConnection = null;
public $isConnectionActive = false;
private $dbServer = null;
private $dbCatalog = null;
private $dbUser = null;
private $dbPassword = null;
}
This class handles opening and closing of the connection on any pages.
It sounds that you want to make your php connections persistants , in that way and if it is so , then you have to create a PDO Object with the required parameters to create a new PHP PDO Object that will attempt to connect to mysql , and in the object instanciation , try to pass persistancy option value to true , you may have available in every php scripts the same PDO Connection Objetc but you will end up to face issues with that way ... but it is not reconmmanded as PHP Programming Best Pratices ... the best way to do so is to include a connection file for every script in your project. Read PHP Documentation for Persistant Connections in order to learn more about Issues found for these Connection Objets especially for recent php versions. PHP Announced that Persistant Connections are on the way to be dropped from futur version as it may increase server workload with persistant ressources ... Sorry if it is too late

Will php autoreconnect to MySQL?

$con = mysql_connect("localhost:".$LOCAL_DB_PORT, $LOCAL_DB_USER, $LOCAL_DB_PASS);
mysql_select_db("hr", $con);
mysql_query("set names utf8", $con);
while(true)
{
do_stuff($con);
sleep(50);
}
If connection timesout in 50 seconds,will $con still work?
If the connection times out, it won't work.
To answer the question from the comment, to cope with the problem, refer to php.net manual page for mysql_connect() which says:
If a second call is made to mysql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned.
so if you want to make sure you always have an open connection, just try to open a new one with the same arguments after the code you substituted with sleep() is done executing.
Simple answer: why don't you try it and see?
I believe codeburger is correct: if the MySQL connection times out, then it's gone. You could use a persistent connection with mysql_pconnect. You will need to call that function after sleep each time but it will use an existing connection, saving overhead.

Categories