Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAdam Zuckerberg
22,248 PointsWhich type of connection do we use: MySQL, MySQLi or PDO?
I am confused by the fact that whenever I go online to learn about PHP MySQL I see three different types of connections. I am totally confused.
1.) Do you just use the connection once in a config.php or database.php file and then whenever you have a query, you just refer to that already-open connection OR do you make a NEW connection for EACH query? 2.) If we see mysql() do we ignore and just use mysqli() instead? 3.) Since I want to do 10 things and for each of them I find separate information with a 30% chance of being written in one of the 3 codes, I am getting stuck. I would like to pick ONE method of connecting, but I can't always translate from mysqli to PDO or vice versa so.....
Can you mix and match and having mysql(), mysqli() and PDO all in the same code? And what about the config file, is it best to choose one of these? And if you connect with one, does the query then have to be in that format? For example, if you have one config file and you use mysqli syntax, can you not write a PDO syntax query in the code.
I am so confused and can't find any Treehouse resources to answer these types problems I am now having.
2 Answers
J Andrew Scott
30,626 PointsIt's typically best practice to open one database connection and reuse that connection throughout your project. Opening new connections is pretty resource-intensive so you want to keep it to a minimum. Database connections are type-specific so, for instance, you can't call mysql_query()
on a PDO
connection. Basically, you want to pick the connection type your are most comfortable using, open one connection, and re-use that connection with the appropriate functions for its type.
Kazimierz Matan
13,257 PointsOne connection and reusing it if possible.
I have never used mysql() or mysqli(). For for a few years I use PEAR DB abstraction layer. I know it is not under active development now, but it works great for me in my current projects. For new ones I will probably use PEAR MDB2.
I agree with J Andrew Scott. Using many connection is not a good idea. Mixing various types and connections, different types of syntax, will make your code hard to read, understand and troubleshoot.