Choosing the right MySQL connection for PHP - php

There seem to be a lot of choices for MySQL connection from PHP. I guess they all offer different feature sets. I just want to run a simple query, and so I'm attracted to the simplicity of mysql_connect(). Is this OK or are there any considerations I'm missing
Thhanks

If you just want to run a simple query, there really is no difference. If you're working on something bigger, use mysqli or PDO instead so you can use it's features. Especially prepared statements is something you really want to use.
I would just forget about the old mysql-library. Mysqli is not harder to use, but it's a big improvement.

Use mysqli instead. It has the same simplicity and it is the improved version of mysql_connect
See documentation here.

Even if you are dealing with a single query or a very simple project, use PDO.
It's how DB stuff it's done nowadays and will likely be done in the future. I think that learning the legacy libraries (mysql, mysqli) is not a good deal right now. The learning curve is quite the same, and with PDO you have a basis for doing anything you want (e.g. changing DBMS).
And, even if you choose to use the legacy, DBMS-bound libraries, please don't use mysql, and do use prepared statements (both mysqli and PDO have them). Don't do stuff like:
mysql_query("SELECT * FROM users WHERE username = '$username' AND password = '$password'");

Related

learning mysqli and pdo

I'm a php and mysql beginner, and I'm currently learning a section called "Accessing mysql database from web with php", in this book, the author only use the example of mysqli, but when I searched the google, I found pdo is somewhat better than mysqli, my question is: should I escape the mysqli one in the book and only learn pdo (from the web)?
Yes, absolutely go straight to PDO.
First, know that you should almost ALWAYS do parameterized queries when taking input from a client. PDO is SO much easier in that regard. (I say 'almost" because you can sometimes do things to 100% separate the client from the database via PHP)
Second, PDO is way more compact, so it needs far less lines of code.
Are there good tutorials on how to use PDO?
Bottom line: you have to learn it sooner or later. Why not sooner?
The problem with all mysqli examples - they cover only basic cases (and even with them being enormously wordy and bloated).
But when you trying to use mysqli in whatever real life application, it turns to be a real nightmare when dealing with prepared statements. Just try to bind an array of values into IN() operator and see.
So, to save yourself a ton of time and nerves, better go straight to PDO, it is reasonable and handy driver. You may start from PDO tag wiki here
You should follow the book first and then learn about prepared statements with PDO. There isn't really a right or wrong approach so there's no harm in learning both.

Using mysqli_ functions with mysql_ connection?

I have written some code that is using mysqli_ a lot. The problem is that I now need to integrate this code with code that is using mysql_, and takes care of connection, authentication etc. I don't want to create a second connection, but mysql_ lacks a few features, for example, prepared queries. So I'd like to somehow magically "import" the connection into mysqli. Is this even possible? If so, how can that be done?
Nope, that's impossible.
By the way, prepared statements is not the only way to make queries safe.
It's placeholders that everyone should use, and they not necessarily have to be implemented using prepared statements.
While placeholders can be easily implemented using mysql_* functions as well
A connection resource created by mysql_connect can't by reused with the MySQLi extension. You will either have to handle the connection in your current code or refactor the old code.
This is not as hard as it may sound. MySQLi also has a procedural interface and you can use the extension just like you do with the old MySQL extension.
The biggest benefit of MySQLi is the object oriented interface which would make refactoring a bit more complicated. MySQLi natively also supports (wraps into methods/functions) MySQL features like prepared statements, transactions and connection charset, but this doesn't mean you can't submit a START TRANSACTION or SET CHARSET utf8 just like you did with mysql_query
Hope this helps. If you have more specific questions regarding the refactoring feel free to ask :)
As F4r-20 pointed out, you could just change the way you connect to the database and replace the mysql_ functions with msqli_ ones!
Try to decide what you are going to use BEFORE you start a project, not in the middle. Preparing saves a lot of time and issues like this.
PS. I would use PDO next time. It is easy, fast, OOP and supports multiple database types!
Edit: since you don't have access to the credentials or how you connect to the database, you will have to use mysql_, change the connection to mysqli_ or make a new connection... Sorry :(

Converting from mysql_query's to prepared statements (mysqli/PDO)? Necessary?

I have been learning PHP and MySQL over the last few weeks, and I'm just now hearing about prepared statements and PDO/mysqli. I did some reading and people are saying that stuff like:
$getFromDatabase = mysql_query("SELECT * FROM table WHERE userid='$id'");
while($row = mysql_fetch_assoc($getFromDatabase)){
stuff();
}
...won't work anymore. I use stuff like that pretty frequently in my code. I also am reading a lot about how prepared statements are much better protection against injection. I've got a thorough understanding of how it is better, but is it so much better that it's worth switching away from mysql_real_escape_string()? Is it necessary to switch to Mysqli or PDO? In what situation could mysql_real_escape_string() be bypassed where a prepared statement couldn't?
It's necessary because mysql_query is, in software terms, an ancient artifact. It's the Model T of MySQL database interfaces, clunky, unreliable, and downright dangerous if not used exactly as you should. If you're not extremely careful you will make a mistake, and even a tiny mistake will not go un-noticed if someone uses an automatic SQL injection bug detection tool on your site.
Basically you're living on borrowed time with mysql_query.
If you use mysqli or PDO and are diligent about using placeholders then the risk of a SQL injection bug is very low. It may take about half an hour to figure out how to convert your old code to these new methods, there really isn't a steep learning curve, and that knowledge will save you a lot of trouble in the future. Converting existing code usually isn't too big a deal if you use mysqli and basic placeholders. I bet you even find some serious bugs while patching things up.
In terms of benefits, you won't need to make any mysql_real_escape_string calls, you can just use bind_param, and you won't have to worry about missing an escape on one of your variables. It's actually a lot less work in the long-run.
Additionally, using ? or a named placeholder like :id makes your queries significantly easier to read, debug and maintain. Further, you can use the same statement repeatedly and bind different values to it, ultimately making your application faster.
It is possible to write safe code with mysql_query but why would you? The interface is listed as deprecated, which is the preliminary stage to it being removed from PHP entirely. If you want a future-proof application, it's best to use one of the supported interfaces.

PDO and CodeIgniter - is it secure?

I dont have any previous experience with PDO, so my question may sound too simple.
I heard few times that PDO is better than mysql/mysqli in terms of security ,and since Codeigniter is supporting PDO driver, I decided to make the change in my new project.
but as I'm aware of Codeingiter doesn't use prepared statements, and (I think) it missed the point of using PDO, is that correct, and is it insecure?
So my question: is using PDO driver with codeigniter considered insecure?
And, does that mean I must take care of the basic security by myself?
All query calls are escaped in the simplified $this->db functions, such as delete() and get_where(). This adds some automated security.
If written too slobby, you may grant access to users to edit other users content for instance. So there's no magical solution to full security. The more detailed you are, the more correct your code will work for you.
If you need custom queries, you can do like this:
$int_user_id = 1;
$this->db->query("
SELECT *
FROM users
WHERE id = ?
", array($int_user_id));
Note: To implement IN () and LIKE, you need to escape accordingly, and not insert through array() and ?.
query()
escape()
1. Database Support
The core advantage of PDO over MySQL is in its database driver support. PDO supports many different drivers like CUBRID, MS SQL Server, Firebird/Interbase, IBM, MySQL, and so on.
2. Security
Both libraries provide SQL injection security, as long as the developer uses them the way they were intended. It is recommended that prepared statements are used with bound queries.
3. Speed
While both PDO and MySQL are quite fast, MySQL performs insignificantly faster in benchmarks – ~2.5% for non-prepared statements, and ~6.5% for prepared ones.
From what I know (CodeIgniter newbie ;)) it takes care of security pretty well with ActiveRecords. I don't know if it's using PDO or not, but it's pretty darn easy to use, queries look really clean, and it has query caching.

PHP PDO and MySQLi [duplicate]

This question already has answers here:
mysqli or PDO - what are the pros and cons? [closed]
(13 answers)
Closed 9 years ago.
I just finished an introduction course in PHP, and throughout the stackoverflow forum people have recommended that I switch to PDO, prepared statements or MYSQLi, I briefly checked the manual but most of it went over my head.
I've been using mysql_* functions up till now so these concepts are new to me. I think they are used to access and perform database specific actions, but I'm not sure.
So what is the difference between PDO, prepared statements and MySQLi, are they different features that accomplishes the same task? Are they compatible in a script or is it "choose one or the other"? And lastly which offers the best performance?
Update: Thanks for the answers, I'll be hunting for more PDO tutorials.
For reference I also found the following posts useful:
Which one is fast and light - mysqli or PDO
mysqli or PDO - what are the pros and cons?
At the basic level the mysql, mysqli and PDO extensions all answer the question how do I talk to the database? They all provide functions and functionality to connect to a database and send and retrieve data from it. You can use them all at the same time establishing several connections to the database at once, but that's typically nonsense.
mysql* is a very simple extension that basically allows you to connect to the database, send it SQL queries and not much else.
mysqli improves this (as the name suggests) by adding parameterized queries and a few other things into the mix.
PDO is an extension that abstracts several database drivers into one package, i.e. it allows you to use the same code to connect to MySQL, Oracle, MS SQL Server and a number of other databases without needing to use database specific extensions or rewrite your code when you switch databases (in theory at least). It also supports parameterized queries.
If you know you're going to be using MySQL exclusively, mysqli is a good choice. Especially since you can use it in a procedural way, what you're already used to from the mysql extension. If you're not familiar with OOP, that's helpful. Otherwise, PDO is a nice object oriented, flexible database connector.
* Note that the mysql extension is now deprecated and will be removed sometime in the future. That's because it is ancient, full of bad practices and lacks some modern features. Don't use it to write new code.
PDO is the "PHP Data Object." I mostly use PDO, so I can only speak on its merits:
Works for many more databases than just MySQL (may not matter to you)
Compiled C, so it's faster (supposedly)
Prepared statements (others have these, though)
SO seems to like it, so you can probably get a lot of help here at least
Various fetch/error handling modes you can set and change on the fly
You ask
So what is the difference between PDO, prepared statements and MySQLi ...
PDO and MySQLi are DB wrappers. "Prepared statements" is a different concept altogether. You can prepare a query that can be executed multiple times, and properly parameterized statements are SQL-Injection safe (though maybe not proof). The latter reason is most of the reason why you should be using PDO (or MySQLi), but prepared statements also bring a level of clarity to the queries.
/* mysql_* version */
mysql_connect("host");
$query = "SELECT column FROM db1.t1 WHERE id = ";
foreach ($_GET['id'] as $id) {
$id = mysql_real_escape_string($id);
$result = mysql_query($query . "'$id'";
while ($row = mysql_fetch_assoc($result)) {
echo "$row[column]\n";
}
}
//NOTE: it would probably be better to store the resource returned by
//mysql_connect and use that consistently (in query/escape)
/* PDO version */
$pdo = new PDO('mysql:host=HOST', 'user', 'pass');
$query = $pdo->prepare("SELECT column FROM db1.t1 WHERE id = ?";
foreach ($_GET['id'] as $id) {
$query->execute($id);
echo $query->fetch(PDO::FETCH_COLUMN);
}
//Notice that you skip the escape step.
You can do essentially the same with MySQLi, but I prefer PDO's syntax. It may be faster too, but I could be making that up. There's also the PEAR MDB2 that rarely gets spoken of, and I'm sure many more. Since PDO is built in, I would go with it.
If you're used to the mysql_xxx functions, then I would starting by moving across to the MySQLi extension instead.
You could use PDO instead if you wish, but this would only really be worth it in the first instance if you need to start supporting multiple databases. For your purposes, I'd suggest switching to MySQLi, as it'll be easier for you, and you won't be getting the benefits of PDO right away anyway.
The functions available with MySQLi are pretty much analogous to the mysql_xx functions you're used to; it's generally possible to take existing code, do a direct swap between them, and the code should continue working just fine.
So that's a good place to start -- get your code using mysqli_xxx instead of mysql_xxx`.
If possible, I'd recommend using the object oriented syntax rather than the procedural syntax. MySQLi supports both, and the procedural syntax will be closer to what you're used to, but the OO syntax is more flexible in the long run, and really isn't that much different once you're used to it.
Once you've got your code converted to using the MySQLi library, and you're comfortable with the basics, you're ready to start using the more advanced features like prepared statements. But get yourself comfortable with the basics first.
Coming from the same point of view as you. From my perspective I don't think the difference is truly noticeable (depending on what you're using it for). It looks like PDO is simply a database api that merges ALL of the other database api's into one. So if you needed to connect to a MS Sql server and MySQL server, you could simply call on the PDO api and specify the driver for the specific db. My guess is also that any future features and abilities in MySQL will be only available in PDO. So basically just use PDO to ensure that you have access to all the latest features.
One big advantage of PDO is platform independence. This means that you can migrate to a different DBMS at some point without having to recode all of your function calls. This is how things are typically done in Java (via JDBC), .Net (ADO) and most other environments. The advantage is not just that you can switch DBMS per se, it's also that you have only one API to learn.
As regards your question, the PDO layer provides the facility to do prepared statements. The idea behind prepared statements is that you create placeholders for the parts of your SQL statement that will not be known until run time. Many learners start off by creating SQL as a string which gets executed by calling mysqli::query($someQuery). This is problematic for many reasons, most prominent of which is the vulnerability to SQL injection (see stackoverflow.com/questions/5315351 for a similar question and answer). With PDO, you can avoid SQL injection and all of the problems of handling characters such as quotes, backslashes etc. The end result is that your code is more secure, readable and predictable.
If you've already figured out how to use mysqli then using PDO is not much different. The linked question and answer above shows an example of a query being submitted using PDO prepared statements which should act as a useful guide.
So what is the difference between PDO, prepared statements and MySQLi, are they different features that accomplishes the same task?
The difference is fairly simple.
PDO is usable with prepared statements and mysqli is not.
Just run some usual queries with both API using native prepared statements, and you will clearly see the difference.

Categories