Using mysqli_ functions with mysql_ connection? - php

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 :(

Related

mysqli_* or mysql_* performance?

In the php.net site, they say that those who use mysql4.1 next to php5 or higher is required to use extremely "MYSQLI_" instead of "MYSQL_."
He wanted to know just one thing, it influences the performance of the site, several problems with site is down due to the database (this on any server).
Already using various solutions. For example, CACHE HTML pages.
But my doubt is really about on MYSQLI_ *, when we use it, she connects to the server and the specified DataBase. According to the php.net site is mysql mysqli improved and optimized mysql4.1 +.
I wonder if the traffic with a large MySQLi give better performance to the site.
PS.: I know the difference "mysqli" and "mysql", taking into consideration the PHP programming and structuring of MYSQL4.1+ (which has new types of columns). What I want to know is on multiple connections.
This question is about performance, thanks
You should read this:
http://blog.secaserver.com/2011/07/php-driver-mysql-mysqli-pdo-mysql/
mysqli provides better performance and increased functionality and as Evert said, it is especially noticeable if you use mysqlnd.
A common comment here at StackOveflow whenever we see code using mysql_* functions should answer your question:
Please, don't use mysql_* functions for new code. They are no longer maintained and the community has begun the deprecation process. See the red box? Instead you should learn about prepared statements and use either PDO or MySQLi. If you can't decide, this article will help to choose. If you care to learn, here is good PDO tutorial.
Yes, MySQLi could give better performance to your site.
You can use persistent connections, which basically share the same idea of the well known connection pooling, but while the connection pooling is used in java development mostly(usually performed directly by the webserver, e.g. Apache-Tomcat), persistent connections are managed by MySQL and PHP.
Besides, MySQLi could help you to secure your queries, by adopting prepared statements.
Mysqli extension provides built-in cleanup handling code, which includes:
Rollback active transactions
Close prepared statements (always happens with PHP)
Close and drop temporary tables
Unlock tables
Reset session variables
Close handler
Release locks acquired with GET_LOCK()
All these features could help you to give better performance and security as well.
For more informations, you can refer to:
http://php.net/manual/en/mysqli.persistconns.php
The mysql_ functions are no longer maintained and deprecated. The mysqli_ functions will perform better, especially if you use the mysqlnd (native driver).
Stop using deprecated API's!

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.

Choosing the right MySQL connection for 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'");

pdo and mysqli in the same project

there is a problem, if in my project i use mysqli for the most part of the project and for a specific query to another db use the pdo?
I'll probably have to do some queries to another databases, but i prefer using mysqli in terms of performance for the rest of the project.
I don't know what is the SGBD in another databases for now.
It is possible to use multiple database access layers within the same application without issue. From a readability/maintainability standpoint, it's recommended to use just one. If you're not seeing good enough performance from PDO, it's okay to use mysqli_ for a performance sensitive part of your application as long as you recognize the tradeoff you're making. Run some simple benchmarks to prove your case. Also, please keep in mind that if you're using PDO and mysqli_ connecting to the same database on the same page you'll be creating an extra database connection. One more thing to keep in mind; No matter what your database access layer, using parameterized queries to protect against SQL injection is strongly encouraged. Parameterized queries are support in both PDO and mysqli_.

Should I have to upgrade my website to PHP MySQLi or PDO?

I have designed a website before 5 years using PHP MySQL and still works fine without any issues. I heard MySQL is officially deprecated as of PHP 5.5 and has been removed as of PHP 7. Also, PHP offers three different APIs to connect to MySQL (like MySQL, MySQLi, and PDO). My web server is updated frequently.
I understood, I have to move to newer API like MySQLi or PDO for safety. Now I am confused whether to choose MySQLi or PDO. Also, Is there any compatibility/migrating options available for such case?
Lets take a look at both of these extensions.
PDO
PDO is database neutral - You only need to learn one API to work with dozens of databases
So if you decide to move to another database, the only thing you would be changing is the DSN(data source name).
Support of both name and '?' placeholders for prepared statements.
Drupal uses PDO.
Mysqli
On the other hand Mysqli is designed specifically for Mysql databases and is recommended by Mysql. Mysqli works with Mysql and MariaDB databases.
Support of only '?' placeholders for prepared statements.
Joomla uses Mysqli
Conclusion
There are many conflicting arguments weather Mysqli or PDO runs faster. Both Mysqli and PDO use the same underlying drivers to access the database making the performance not worth comparing.
So there is no clear winner when working with Mysqli or PDO. But let's say you use Mysqli and then later you want to use another database, it would be a difficult transition.
The main strength of PDO over Mysqli is name placeholders for prepared statements and which is why I chose PDO over Mysqli.
The answer is fairly simple.
If, like majority of PHP users, you are going to use database API functions right in the application code, without any intermediate wrapper, then PDO is your only choice, as it's a sort of wrapper already, automating many operations that with mysqli have to be done manually.
No, there are no migration options, because the very approach is changed dramatically: instead of placing variables right in the query, they have to be substituted in the query with special marks. There is no way to automate this process.
PDO and MySQli both are used for database connection and both have their own advantage. In closer look PDO wins the battle but if you really stick with only one database provider then my personal best choice is use MySQLi.
You will also extract some good points from: http://code.tutsplus.com/tutorials/pdo-vs-mysqli-which-should-you-use--net-24059

Categories