Integrating PDO with an existing MYSQL/PHP App - php

I am building some new additions to an existing WebApp. The old code was written using mysql functions. Changing the entire application to use PDO would be a VERY man-hour-intense thing to do. However, for all new code, I'd like to begin using PDO.
Are there any concerns I need to be aware of for using PDO within an existing application that does NOT use PDO to interface with the database? It's no problem to connect to the DB using both/either of these options at the same time when a page is loaded, correct?
While I'm at it - I am interested to know how big the need is to close a PDO connection after a page loads - or is it fine to leave the connection open?
Thanks all.

There's no need to close any type of database connection when a page finishes loading - PHP always does this for you (unless you make the mistake of enabling persistent connections).
However, if you use PDO AND mysql_ in the same page, connecting to the same database, it will consume twice as many connections (while the page is executing) on the server. This may or may not be a problem.
Personally I would recommend that you remain consistent within the application if you don't want to refactor it to use PDO throughout.

Related

Reusing a PDO connection after execute?

I would like to know if it's correct to re-use a PDO db connection multiple times ?
For example, I set it up in my controller then pass it as a parameter in a constructor of a class, is it correct to call the same connection (by using a function like get_Database) thoughout all my functions in the class and even pass it as a parameter in another class construct to continue working with the same connection ?
Or should I reopen a connection at some point ?
I was able to get it working by simply passing it around, however I am not quite sure if this would be performing well when going live.
Yes, you should reuse the connection.
Or should I reopen a connection at some point ?
The only reason to open a new connection is if connecting to another database. Otherwise, throughout a single script only one connection should be used.
To achieve this it is important to try and avoid using a static singleton throughout your application, rather learn about dependency injection to design your code to share the same PDO instance to every function or class that needs it.
however I am not quite sure if this would be performing well when going live.
As commented, if you reopen a connection often, it will be a lot slower.
There are many dependency injector's out there, and it is almost certainly a matter of opinion, but I like Auryn. Learning about it should help you design code where it is easier to share a single PDO instance, amongst others.
Yes, this is OK and it is better than connecting to the database many times.
The documentation even suggests to use the opened connection between calls to your php script / application:
Many web applications will benefit from making persistent connections to database servers. Persistent connections are not closed at the end of the script, but are cached and re-used when another script requests a connection using the same credentials. The persistent connection cache allows you to avoid the overhead of establishing a new connection every time a script needs to talk to a database, resulting in a faster web application.

PDO, Injection and conserving server resources

I'm refactoring PHP code to move from mysql_* and mysqli_* functions to PDO, and would like to accomplish this as efficiently as possible.
I use a file I call 'core.common.php'. I initializes the PDO database access object, has $_SESSION management features, and other features such as generic message and error notification functions (in the form of s.) I use the MsgBox() and ErrBox() functions extensively while developing and debugging. This file gets included at the top of every PHP-generated web page.
I have managed, at least through some testing, to successfully pass the PDO object (by injecting the PDO object in the __construct method) to classes that require database access.
It seems to me that this approach, while it still works so far, would only apply to each visitor of the site... Each visitor can use the same PDO connector throughout all pages they visit on the site.
My real questions are...
What happens when there are many visitors ?? Does each get their own PDO instance ? Would this mean that there would be many instances of database connections ?
The reason I'm asking is the host I currently use has "limited my resource usage" due to... according to them... "excessive resource usage". It is a "shared server". They suggest upgrading to a VPS (Virtual Private Server), and, of course at additional cost.
Is the host scamming me for more $$ ??
What, in the eyes of the Pros here, would be my best approach to this issue ?
And... Absolutely for all... Be critical and specific.
Any ideas are greatly welcomed !
What happens when there are many visitors ??
Exactly the same thing that happened with mysql and mysqli functions.
Does each get their own PDO instance ?
Yes. In a way.
Would this mean that there would be many instances of database connections ?
Yes. Just like it was with mysql functions.
the host I currently use has "limited my resource usage" due to... according to them... "excessive resource usage".
Make sure there is only one connection per script instance. According to your description it is already so, but just to be sure. That could be only issue with PDO. Also turn off persistent connection if used.
Regarding other aspects of this excessive usage, you better start a separate question, to ask recommendations on how to profile your code to get to the bottleneck.

PHP has stopped implicitly detecting MySQL database links

On one of my servers I've had a strange thing happen.
Normally, when a script does mysql_query($query) it just works if mysql_connect() was successfully called beforehand.
Now, it isn't working more than half the time. Now I've suddenly had to edit an entire shopping cart worth of mysql_query calls to include what used to be an optional DB link. In other words mysql_query($query, $db_link) is now what the code looks like.
I've done this temporarily so that visitors can still use the site but I really need to know what could have caused such an event.
Is there some setting that could have somehow changed in one of the php.ini files that would cause this? I know I wasn't touching them when this happened and I was the only one logged into the server at the time (as far as I can tell).
Calling mysql_query() without a connection parameter will use the most recently established connection. So as long as you're only connecting to one database, you won't see any problems.
From the docs:
If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
If you add or include some new code that's connecting to a different database though - perhaps a hit tracker, or an analytics tool, for example - then that can break your existing code because it establishes another mysql connection - and any of your queries that happen after that new connection is established will now be using the wrong connection.
This will happen even if the extra code is properly written and always uses its own connection identifier - it won't have problems of accidentally using your connection, but your code will still accidentally use its connection.
To safely use mysql_query(), you really need to keep track of the database connection, and use it in every query.
All that being said - if you're making changes to all the mysql_* calls anyways, please consider switching to mysqli. The mysql_* functions are deprecated and no longer supported. The mysqli extension can be almost a drop-in replacement, and also provides support for features such as prepared statements.
The PDO extension is another possible replacement, but would require a bit more rewriting when switching from using mysql_*.

Best practice for handling mysql connection in a social network system

Currently, I am dealing with a social network startup. We use php & mysql for back-end development. I have a datamanager.php that have functions which handles the sql connections and queries. I have several functions like signup, login, get_profile, etc.
I have 2 choices for handling mysql connection
1) create a globally reachable $connection variable with mysqli_connect(); and don't close the connections until I finish all the database operations.
2) create a function namely db_connect() that returns the connection variable in each database functions. Also, in each database function like login, signup, I close the connection with mysqli_close(); and get another connection variable with db_connect();
So, which choice is better for handling mysql connections and why ?
It's better to keep the MySQL connection open as of performance. Better use a class to handle all mysql connections and somehow pass the instance of the class (i.e. the object itself) to all other functions/classes which need it. Within the class you could establish the connection ONCE and than keep it!
Firstly, on the assumption that you are building something that needs to have a long shelf life, and scale to lots of users, with a roadmap for new features, I'd encourage you to use an off-the-shelf PHP framework; Zend or Symfony seem to be the front runners. These frameworks provide a lot of the plumbing for you, so you won't have to worry about database connections.
However, specifically answering your question, I'd encourage you to use mysql_pconnect - it frees you up from worrying about opening and closing connections. You do need to read the manual, it's not totally straightforward...

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