This will probably sound pretty dumb. I've got a mysql function containing the following...
#mysql_connect()
#mysql_select_db($databaseName,$link);
mysql_query($sql,$link);
mysql_error()
mysql_fetch_array($result,MYSQL_ASSOC)
mysql_num_rows($result)
Can I just bung an i after mysql like this...
#mysqli_connect
mysqli_query($link, $sql);
mysqli_error($link)."]";
mysqli_fetch_array($result,MYSQLI_ASSOC))
mysqli_num_rows($result);
The first two I know are ok but what about the others? I'm not sure those functions actually exist as straight swap mysqli versions. Can't seem to find much info about them.
What would there mysqli equivilent be?
Can I just use mysqli_connect and mysqli_query but use the old mysql functions for the others? Do they work together like that
Here is the "book" area of the PHP manual showing you EVERY mysqli function available. Your assumption is pretty much correct, a lot of the naming convention applies with just adding 'i' but to be sure that it exists, take a peak here: http://php.net/manual/en/book.mysqli.php
One of the strengths of the MySQLi extension is it's more object oriented. I'd recommend moving to that method as it's easier to work with.
Related
Up until recently I was using mysql instead of mysqli or POD but as PHP has announded that it will not support mysql so i have decided to move to mysqli. But I have read several blogs/article everyone says that for security purpose mysqli is better than mysql but performance wise mysql is better. If you are planning for high traffic website, then this small difference in performance may cause problem. Apart from this performance issue I have found that mysqli and PDO is little complicated to use. For example for select function we can directly use this in my sql:
$res = mysql_query("SELECT * FROM `summary` WHERE id='35' limit 1");
$row = mysql_fetch_array($res);
But in mysqli we have to use this something very complicated query for select/update/delete/insert etc. Is there any way i can use almost similar code for mysqli as well?
If you are planning for high traffic website, then this small
difference in performance may cause problem.
Have you actually tested this out with your code? In many cases it is a negligible difference at best. So I would not worry. Typically these dire warnings of speed differences mean that something that took 1.5 seconds to complete would now take 1.6 seconds.
Besides, PDO adapters are simply the future. That is why they allow for prepared statements via ORM (object-relational mapping) or straight queries (see the example below).
But in mysqli we have to use this something very complicated query for
select/update/delete/insert etc. Is there any way I can use almost
similar code for mysqli as well?
Yes, you can. mysqli has the capabilities to allow you to use pure MySQL queries without using PDO structure:
$db = new mysqli('localhost', 'user', 'pass', 'demo');
$result = $db->query("SELECT * FROM `summary` WHERE id='35' limit 1");
while($row = $result->fetch_assoc()){
echo '<pre>';
print_r($row);
echo '</pre>';
}
Also, if you are truly worried about MySQL performance, then just run a script like this MySQL Tuning Primer script regularly to performance tune your MySQL install. That will do more to improve performance than obsessing over mysql versus mysqli in PHP.
After a lot of responses on a number of different posts I've seen, I'm stopping using mysql and am trying to upgrade my site to use mysqli.
My question is, based on the functions of mysql that I list below (which are the ones I currently use) can I do a blanket replace on 'mysql_' for 'mysqli_' and not break functionality? I've already done some research on each of these functions and none of the mysqli versions look like they wouldn't work, but I just need to be sure before I swap them all out.
query
fetch_array
connect
select_db
error
real_escape_string
num_rows
fetch_assoc
free_result
Check out this SO question which provides answers to at least most of your functions.
For example:
mysql_connect will be replaced by mysqli_connect
mysql_error will be replaced by mysqli_error and/or mysqli_connect_error, depending on the context
mysql_query will be replaced by mysqli_query
I have just begun working with MYSQLi instead of MYSQL, and I have run into a huge annoyance: having to connect to the database every single query and such. Why do I have to do this now when I didn't in old MYSQL? Or is there a way not to have to do this?
A couple examples:
Mysql:
mysql_query("SELECT id FROM table");
Now in Mysqli I always have to do:
mysqli_query($db, "SELECT id FROM table");
also I have to do this with:
mysqli_last_id($db);
and
mysqli_real_escape_string($db);
I have tried to find the answer to this all night, but I can't find anything.
There are some things to clarify
You don't have to connect every time. Connecting to database is different thing, one when you're calling mysqli_connect() and you should do it only once per application.
So, you're talking of just using connection resource variable.
Yes, you have to pass it in every function. Not a big deal, nothing to talk of.
The only issue could be with variable scope. Use global $db; inside a function.
Moving to mysqli just mechanically, using new functions old way makes absolutely no sense. If you want to keep using mysqli_real_escape_string in the application code - don't bother with transition at all and keep with mysql.
The only reason (quite weak though) for move - to use prepared statements.
Mysqli's support for prepared statements is awful
So, better quit mysqli and go for PDO
Nevertheless, using raw API functions, be it mysql, mysqli or PDO, is ugly. One have to adopt some abstraction library to be used in the application code instead.
Yeap, don't use mysql_* functions, they are deprecated. Use PDO instead
http://www.php.net/manual/es/pdo.construct.php
$pdo = new PDO(/* Connection options */);
$rows = $pdo->query("SELECT * FROM table")->fetchAll(PDO::FETCH_OBJ);
foreach ($rows as $row) {
print_r($row);
}
$pdo->query("INSERT INTO table SET field1 = 'value1'");
Give a try to DALMP Database Abstraction Layer for MySQL using PHP. is uses pure mysqli and connects to database only when needed, when possible get the results from the cache, with out touching the database.
Examples of using the cache can be found here Cache & prepared statements
So as I'm sure anyone who's been a regular on SO has noticed, the mysql_ functions are going to be deprecated and it is suggested that one use mysqli_ or PDO instead. Thus, I decided to transition over to mysqli by doing a simple find/replace in my code, replacing every mysql_ with mysqli_. This seemed to work okay in Dreamweaver, and I got no syntax errors or anything. All the new mysqli_ functions were colored blue, meaning that they were recognized as valid functions.
However, when I saved everything and ran the code, I noticed that any code having to do with mysql had become nonfunctional. Undoing the replace solved the problem.
Is my server perhaps not supporting the mysqli functions? I know that it's running php 5 and mysql 5. Is there perhaps something else that you have to add to the code? What am I missing?
It's a good time to switch now, since PHP 7.0 removed the ext/mysql functions from core.
Consider the following legacy code
$res = mysql_query($sql);
The mysql_ functions were lazy, in that it would use whatever connection was open. But mysqli_ is not only not lazy, it's an object, not a connection resource (which is what mysql_connect() would return). Look at these lines here for connecting to the database
$mysqli = new mysqli('host', 'username', 'password', 'db');
$mysqli = mysqli_connect('host', 'username', 'password', 'db');
Both of them give you the same thing...
Returns an object which represents the connection to a MySQL Server.
Yes, that's right. Even the procedural connection function returns an object. The simplest way to use it is directly in is object form
$mysqli->query($sql);
The procedural functions are simply wrappers for this. But they are NOT lazy. Check out the difference
mysqli_query($mysqli, $sql);
The single largest gotcha in this (why a simple find and replace of mysql_ with mysqli_ fails) is that most of the mysqli_ functions require you to pass the connection object as the first argument. It's also important to note that results are objects as well (mysqli_result class), although their procedural counterparts only require the result set so you can simply find/replace those.
Just to be complete, there's one other gotcha that's less common (this is really old code): mysql_result. This function has no equivalent in mysqli_. You should switch to the full row return functions like mysqli_fetch_assoc($result)
you might wanna check out http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers , which should tell you just about all you need to know about migrating mysql_ code, but to PDO, not MySQLi..
you Have to know There are many issues might had be done when you were replacing your code.
Check the installation of mysqli here.
check the configuration of mysqli here.
check the DB connection in tow ways :
** simple connection like natimysql:
$con = mysqli_connect("localhost","my_user","my_password","my_db");
But Now You have to use it like that
mysqli_query($con,"SELECT * FROM Table"); // $con is the connection which is must for executing the sql query
**my best way is dealing with it as new mysqli object like that :
$con = new mysqli('localhost', 'user', 'pass', 'demo');
now you will do it like that :
$sql = "SELECT * FROM Table";
$con->query($sql);
if you checked every query that you had done before You must find one of these errors specially the errors in the 3rd point
you can take a tour in its tutorial here , here or here
Surprised nobody has mentioned that the mysql_ and mysqli_ functions are not exact parallels, therefore a search and replace is bound to fail. Also mysqli_ will generally insist on the database connection parameter (when used in procedural mode, which is what you're aiming fo), where mysql_ would just grab whatever connection had been opened earlier in the code.
If you have debugging enabled, you should be able to work through the errors.
The most common 'gotcha' is that there is no mysqli equivalent of mysql_result(), which people often used when getting a single result. I'd be willing to bet your code is scattered with "mysqli_result()" calls, which will all fail.
That's the basic fix. The 'good' fix might be to use a dedicated class for all your SQL calls, so that there are only a handful of uses of the mysqli functions in your entire codebase, and all in a single file. That way when you refactor you don't need to search through mountains of files all with a variety of different uses of various mysqli functions.
If you "Need some authoritative sources for MySQL -> MySQLi migration" I can recommend a website called Google ;-) Type in "MySQL -> MySQLi migration".
For instance, this 'for Dummies' page shows you the differences between the various functions that you'll need to address to get your code working.
http://www.dummies.com/how-to/content/how-to-convert-mysqli-functions-to-mysql-functions.html
mysql_ functions are now deprecated
Nope, they aren't yet
I decided to transition over to mysqli by doing a simple find/replace in my code
the problem most likely lies in the fact that mysqli functions has reverse parameters order and require connection resource explicitly.
Nevertheless, even if you succeed with such a bulk replace, it will do not a slightest good to your code, so, you'd better keep it as is, despite of some errr... overenthusiastic campaign on this site.
There is no reason to hurry. You have at least 5 years until you'd start notice some inconvenience.
The goal of all this noise about mysql functions is not for changing some API to another but for making usual PHP codes slightly more sensible and safe. You won't reach neither of these goals with just search and replace - so, there is no reason to do it at all.
What you really need is a some intelligent way of handling queries, encapsulated in some library class, which will not only improve your experience with running SQL queries but also will move all the API functions into one place where they can be easily replaced to whatever API some folks will decide to force you to use.
I'd like to know if anyone has any first-hand experience with this dichotomy. A few blogs say the mysql extension is faster than mysqli. Is this true?
And I'm only asking about speed. I know mysqli has features that are not present in the older extension.
The MySQL extension is very slightly faster than MySQLi in most benchmarks I've seen reported. The difference is so slight, however, that this should probably not be your criterion for deciding between the two.
Other factors dwarf the difference in performance between mysql and mysqli. Using mod_php or FastCGI, a bytecode cache like APC, or using data caching judiciously to reduce database hits, are far more beneficial for overall performance of PHP scripts than the choice of MySQL extension.
Don't be penny wise and pound foolish! :-)
"It depends."
For example, PHP MySQL vs MySQLi Database Access Metrics and the subsequent comments point out arguments both ways.
If you have a mature database and codebase, do some testing and see what works in your system. If not, stop worrying about premature optimization.
See http://php.net/manual/en/mysqlinfo.api.choosing.php
The overall performance of all three extensions is considered to be about the same. Although the performance of the extension contributes only a fraction of the total run time of a PHP web request. Often, the impact is as low as 0.1%.
According to all the Google results for benchmarks linked by ceejayoz it looks like MySQL is at least slightly faster than MySQLi in all the benchmark tests. I do recommend reading the results for details but just figured I'd post something that directly answered the question and bumps up ceejayoz's answer.
The PHP documentation has a good comparison of mysql, mysqli, and PDO. I know you only asked about speed, but others might find this useful. It talks about the feature differences between the options.
Maybe, this can be a reason to make the right choice :: The Plot to
Kill PHP MySQL Extension
" Yes, you read it right. Recently, Phillip Olson sent to the PHP internals mailing list a proposal to kill the original PHP MySQL extension in future PHP versions. "
In relation to PHP programming language, MySQL is the old database driver, and MySQLi is the Improved driver. MySQLi takes advantage of the newer features of MySQL 5.
Features of MySQLi taken from php.net site:
Object-oriented interface
Support for Prepared Statements
Support for Multiple Statements
Support for Transactions
Enhanced debugging capabilities
Embedded server support
Unless milliseconds matter then don't worry. Surely if you have no need for the extra functionality provided by mysqli then just stick with the tried and tested mysql.
<?php
$start = microtime();
$c = new mysqli('localhost', 'username', 'userpass', 'username_dbname');
$c -> select_db('username_dbname');
$q = $c -> query("SELECT * FROM example");
while ($r = $q -> fetch_array(MYSQLI_ASSOC))
{
echo $r['col1'] . "<br/>\n";
}
$me = $c -> query("SELECT col1 FROM example WHERE id='11'") -> fetch_array(MYSQLI_ASSOC);
echo $me['col1'];
echo (microtime() - $start);
?>
Why when using mysqli oop is there a slight speed increase from using this script with mysql or mysqli procedural style? When testing the above script I get .0009 seconds consistantly more than when using the other 2. When using mysql or mysqli procedural, I loaded the scripts 20x in each different style and the two were always above .001. I load the above script 20x and I get below .001 5x.
MySQLi has two basic advantages over MySQL; prepared statements are a great way to avoid SQL injection attacks. Secondly MySQL (or mariaDB) will do their best to optimize prepared statements and thus you have the potential for speed optimizations there. Speed increases from making the database happy will vastly outsize the tiny difference between MySQL and MySQLi.
If you are feeding in statements you mangle together yourself like SELECT * FROM users WHERE ID=$user_id the database will treat this as a unique statement with each new value of $user_id. But a prepared statement SELECT * FROM users WHERE ID=? stands a much better chance of having some optimizations/caching performed by the database.
But comparisons are fairly moot as MySQL is now officially deprecated. From the horse's mouth:
Deprecated features in PHP 5.5.x
ext/mysql deprecation
The original MySQL extension is now deprecated, and will generate E_DEPRECATED errors when connecting to a database. Instead, use the MySQLi or PDO_MySQL extensions.