trying to understand postgresql via php database connection sharing - php

To say I am new to PostgreSQL is an understatement. As such I have spent a great deal of time in the last couple of days going over the various manuals at http://www.php.net/manual/en/ref.pgsql.php and at http://www.postgresql.org/docs/9.1/interactive/index.html .
Short form of my question:
Do different users (logged in from separate IP addresses) utilize the same connection to a PostgreSQL data base behind the scenes?
Long form of the question:
In a given php script the database connection $connection is defined near the very beginning of script. That connection is then used throughout the rest of the script via $GLOBALS['connection']. Thus in that script a given user simply reuses the same connection over and over again.
A second user using the same script while logging in from a different location also uses a single copy of the connection.
From the manual (at http://www.php.net/manual/en/function.pg-connect.php):
If a second call is made to pg_connect() with the same connection_string as an existing connection, the existing connection will be returned unless you pass PGSQL_CONNECT_FORCE_NEW as connect_type.
So, does this mean that both users are sharing the same connection (unless the PGSQL_CONNECT_FORCE_NEW flag is sent)?

No, every time you run php script - you make new connection unless you're using persistent connections or connection pooler (like pgbouncer or pgpool).
PGSQL_CONNECT_FORCE_NEW flag means that if inside one php script you call twice pg_connect() with same params you really got one connection unless this flag is set.

Related

Minimizing MYSQL connection from webhook callback

I am working on a project that requires my server xyz.com to receive POST/GET responses to xyz.com/callback.php from abc.com(SMS gateway providers).
Below is how i currently handle the responses on callback.php
1. Receive the POST data from abc.com (This post contains a unique ID)
2. Connect to mysql database and UPDATE users WHERE messageId=Same_ID_from_POST_data
This works and data is being updated. However it is causing CPU overload due to the thousands of MYSQL connections. This is because whenever there is a delivery receipt from the api server for each individual message, callback.php connects to mysql and updates the database.
Is there a best practice to minimize the amount of times i connect to MYSQL?
I was thinking of doing the following, i however doubt if it makes any sense.
1. Receive post data from api server as before.
2. Instead of updating mysql, i simply write to a .txt file with the following code
$query.="Update users set status='$post_data_for_status' where unique='$post_unique';
Then after about 10mins i use cron to run a php file that uses mysqli_multi_query($connection, $query) to update the table thereby making it a single connection. After the update i simply unlink the .txt file
Even if the above method will work, i don't know how to do it. I am sure there is a better alternative.
Any ideas please and sorry for long epistle.
What you are looking for sounds like avoiding connection churning, which is one of the benefits we get from using a "connection pool", commonly used in Java/J2EE web applications.
PHP doesn't provide connection pooling (AFAIK). But PDO and mysqli do provide for "persistent" connections, which give some of the same benefit as connection pool (avoiding connection churning.)
For mysqli, prepend "p:" to the hostname in the mysqli_connect.
http://php.net/manual/en/mysqli.persistconns.php
For PDO, include PDO::ATTR_PERSISTENT => true in the connection.
http://php.net/manual/en/pdo.connections.php
Be aware that with persisted connections, the MySQL connection maintains it's state (session variables, temporary tables, user defined variables, et al.) For example, if a client issues a statement such as SET time_zone = '+00:00'; or SET #foo = 'bar';, a subsequent client reusing that MySQL connection is going to inherit the time_zone setting or the user defined variable #foo value; whatever changes to the MySQL session state the previous clients made.

MySQL Variables PHP COnnections

I'm using a PHP web application to connect to MySQL, what I would like to do is set the userID of the client who has logged in and then use that MySQL variables within views and functions to limit data returned.
Currently, I'm simply using:-
SET #UserID = 3;
And then referencing this within views/functions.
Is this a suitable and reliable method to do this across multiple concurrent user sessions? Will this be present for the lifetime of that users MySQL connection (or page load) from PHP and I obviously want to ensure no other connections leverage this. It's set on every page load (or MySQL reconnection from my app).
Thanks all!
As it clearly states in the first paragraph of the mysql variables man page: http://dev.mysql.com/doc/refman/5.0/en/user-variables.html
User-defined variables are session-specific. That is, a user variable defined by one client cannot be seen or used by other clients. All variables for a given client session are automatically freed when that client exits.
e.g. they exist while the php<->mysql connection is kept alive, PER connection, and automatically removed when the connection is closed/terminated. Unless you're using persistent connections in PHP (which you shouldn't be anyways), the mysql variables would basically exist for the life of that particular script invocation, and will NOT be available when the same user comes back with another http request later.
So, strictly speaking, what you're doing shouldn't be a problem (each PHP connection exists more-or-less independantly). But, that said, it isn't the best approach.
I think you've got a "if all you have is a hammer, everything looks like a nail" problem. MySQL is not designed with the request lifecycle in mind, and it shouldn't need to be aware of it. PHP, on the other hand, is designed with exactly that idea.
Instead of:
mysqli_query('Set #UserID=' . $id);
$output = mysqli_query('SELECT * FROM FOO WHERE ID=#UserID');
Why not just use bound variables?

MySQL database connection not closed: what will happen?

I am using PHP to query the MySQL database on my website. Please answer the following questions:
What will happen if I don't use mysql_close() when I am done with querying the database in the end? The connection will remain open? If yes then upto how much time? If no then why?
If I open and close a connection to MySQL at several places in a
webpage, how is the performance affected? i.e. connection is made again everytime some access to database is required on a single webpage.
How is mysql_close() related to performance? Should I open a new connection everytime some access to database is required OR should I keep only one connection and close it in the end?
If I don't close the connection, then if the user is trying to
access some data again, will the new connection be used or the old
open connection will be used?
It will automatically close when the PHP script is done running during destruct phase.
Performance will negatively be affected. Opening a new socket (especially to an external database server) is more expensive and time consuming than just keeping a pointer to the current connection in memory.
See answer no. 2
The access to the data will be performed by a new PHP request. Hence, you will have a new database connection. No problems there.
I'd advise to open your database connection during construct phase, re-use that connection during the entire execution of your script (if it's OO based, assign a class variable for your database connection and use $this->db during the entire script), and close it during destruction (or don't bother at all closing it, as it will be closed anyway, even when not declared specifically).
From php.net :
Using mysql_close() isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.
for performance it depends on situations, how long it is used, for how long it is idle and so on (e.g. long execution). In most cases, there is singleton pattern by which you have one open connection, and make all queries with that open handle. But it's not true all in all, as mysql_connect itself is kind of supports that:
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. The new_link parameter modifies this behavior and makes mysql_connect() always open a new link, even if mysql_connect() was called before with the same parameters.
So basically, mysql_close is not very needed when it comes to short running scripts.
There is negligible performance loss to close a connection, compared to the resource usage of keeping it open when you don't need it. Better to close a connection as soon as you're done with it, and open it again when you need to.
If you use non-persistent connections all opened MySQL connections will be automatically closed when the PHP script finishes execution.

Do I need to connect db every time in php?

I have a Class called User, and have 2 methods, one is "login", another is "register".
Both "login" and "register" requires connect the db. Do I need to connect db everytime ?? Can I have something which connect once only to reduce the time of connecting db? Thank you.
Keeping a connection to the database open requires dedicated resource on both the web server and the database server, and the number of open connections available is often very limited (in the range of 100). The connection process is usually very fast, and shouldn't be a problem. By opening and dropping connections as quickly as possible, it's usually no problem to scale up.
As always, try the simple and lightweight approach first (which would be connecting every time and dropping the connection as soon as possible). From there you can measure if there really is a problem.
Yes you need to connect every time. But you can actually reduce the load of connecting by using mysql_pconnect() as long as your username, host and password is same. This will check if there is any active resource with the same connection DSN. If found, it will then return the same object as long as it it alive, instead of creating a new connection.
Hope that helps.
In that case class User should expect a DB connection object provided in the constructor.
Then the constructor should save it as local variable, and both login() and register() methods would expect that this variable contains a valid connection object.
And, please, use PDO instead of old mysql_* methods. This will give you a connection object, that you can share among all the classes, which require a DB connections
Yes Sir. Everytime a user connects to your application to do a Login Action o Register Action a connection to the DB must be opened and closed at the end. A Keep Alive option will kill your server.

keeping db connection active across pages

I'm a learner. Is there a way to stay connected in to the mysql database as the user is taken to the next page.
For example, the db connection is made, the user is logged in, and then goes to the next page to access a table in the database. Instead of having to make the db connection again, is there a way to keep the previous connection active?
Or does it matter at all in a low-traffic site?
I read a post yesterday about something related to sessions, and the responder talked about sending a "header-type" (?) file.
Thank you.
Yes and no. Once the user goes to the next page, for all intents and purposes they are not connected to the database anymore.
Your script (on the next page) will still need to open the connection for them. mysql_pconnect() will ensure the actual connection they used is still available when they want it next, however, it can also cause excess number of apache/mysql connections to wait around uselessly.
I'd strongly suggest not using it unless your benchmarks show that it provides a significant gain in performance. Typically, for most applications (especially when you're learning), I would not bother with persistent connections. Note the warning in the PHP Manual
it wont matter unless you're getting a ton of requests, but php has a mysql_pconnect (pconnect) for persistent connections to mysql. each instance of apache will keep around an active connection to mysql that can be used without reconnecting.
I believe you're looking for something like mysql_pconnect(), which establishes a persistent connection to the database.
I realy cant understand your question, if you have fetched datas from db you usualy do some stuff with it. And if you want fetch data from db you do usualy this points.
Some Framworks and Library makes this points a bit easiyer.
Here is the usual way of the process.
1. Make connection to the db.
2. Select a db.
3. Send a query to db.
4. Fetch the results.
5. Do some funy stuff with it.

Categories