Do I need to connect db every time in php? - 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.

Related

mysqli object is already closed [duplicate]

I'm trying to pass a session with mysqli connection for multiple queries on the site, but when I try to do a query it outputs a warning "Couldn't fetch mysqli"
$_SESSION['db']=new mysqli($host,$username,$password,$db);
Is it impossible to pass a mysqli connection reference thru session? is there a different method to use?
Yes, it is explicitly impossible.
See PHP Documentation here mentioning in a highlighted Warning: "Some types of data can not be serialized thus stored in sessions. It includes resource variables or objects with circular references (i.e. objects which passes a reference to itself to another object)."
MySQL connections are one such kind of resource.
You have to reconnect on each page run.
This is not as bad as it sounds if you can rely on connection pooling via mysql_pconnect(), but first see more background info on mysql_pconnect() in this article.
Database connections are resources and can't be stored in a session. You'll have to rebuild the connection in every page, or use a persistent connection (PHP 5.3+).
Yeah - you can't pass it through a session. The handle is specific to the request. You might be able to put it in a shared resource like memcache, and fetch the handle when you need it.
However, if your using connection pooling, grabing a new handle when you need (and closing it when your done) isn't a large performance hit.
Always depends on your needs, but yeah, I'd either:
Create a new handle when you need it /per request/ (turn on connection pooling)
Stick the dbhandle in memcache

trying to understand postgresql via php database connection sharing

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.

Is it a good idea to make mysql connections static?

I'm working on a medium-sized (probably) PHP system which had MySQL connections being opened everywhere throughout different files and, made into global variables for the later included scripts to have access to. Since I'm creating another module, I'd like to avoid globals and keeping the same mysql connection for each page request. My current solution is this:
Class Db {
static public $dbConnectionArray = array();
}
For every request, the connections would be saved in the static array and referred back to at a later time. What do you think could go wrong? And why?
Would like to hear some opinions on how to best tackle this as I would love to reduce the number of opened connections per script run (currently, one page request invoked about 6-15 mysql connections to at least 3 different databases).
No need to reinvent the wheel. you can use mysql persistent connections to keep connections alive. (http://php.net/manual/en/function.mysql-pconnect.php)
By using persistent connections, your PHP scripts will reuse the same database connections (as long as the database name & credentials are the same)
Also, if your databases are on the same host, you should be able to use the same mysql connection by using mysql_select_db() function.

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.

Where and when to open a database connection

I am working on implementing use of the mysql class found here in an existing script. The script almost always needs to interact with the database, even if there are times when it does not. What is the best practice in this case? Should I open a connection and keep that open until the end of the script or should I open a connection when I need one, closing it when I'm done, to avoid opening a connection when the script does not need it?
Because connections are rather expensive, as others have pointed out, I'd recommend using a "lazy connect" technique in your database layer. If you have structured your application effectively, your application logic should not be concerned with when connections are opened and closed as this would be encapsulated in the database layer. The database layer, when asked to perform a query, would first check to see if it has an active connection and if not, create one. This way you'll avoid opening connections that are never used and you'll also have a nice separation of logic between your application and the database code.
Well, if you are using a class, the connection should be opened automatically when you instantiate the class, or when the first query is performed. If you never use the class, the connection wouldn't be opened. While it is good practice to close it when you don't need it, it doesn't hurt to let it be closed when the request thread dies.
This can be bad if you don't have a resource limits set in your php.ini file, the request could possible live forever and never close the connection.
If you have a medium-to-high traffic site, you should be thinking about using mysql_pconnect anyways so there is always a connection open and you don't need the overhead of opening one on every request.
Usually you'd only want to open a connection to your database when you need to use that connection. Keeping connections open can increase the chance that part of your code will accidentally, or maliciously through the actions of others, cause unwanted queries to be performed on the database.
That being the case, you should only open the connection before you want to run your queries. If you have a large number of queries, try to open your connection as late in the process as possible.
It is better to have one connection left open for a longer duration than to open and close multiple connections.
If your code is performance-sensitive, then the preferred technique tends to be to use some form of connection pooling and/or persistent processes so that you can open one database connection and then use that connection to service many page requests rather than opening a new connection for each request that needs one.
If your code is not performance-sensitive, then it doesn't really matter anyhow.
Either way, the exact timing of when the database is accessed in the course of handling a specific request isn't that great of a cause for concern.
My personal practice is to open a database connection immediately when a new handler process is spawned, then verify that it's still alive when I start processing each request. The rest of the code is then free to just assume that the connection is available when needed without incurring the cost of connecting while a user is waiting for a response.

Categories