I have used mysql_query() throughout my project; but I've just learned that mysql_ was deprecated as of PHP 5.5, has been removed in PHP 7.
So, I would like to know if I can replace all mysql_ functions with mysqli_ in my project blindly? For example, just replacing mysql_query() with mysqli_query(). Is there any adverse effect?
The short answer is no, the functions are not equivalent.
The good news is there is a converter tool that will help you if you've got a lot of calls/projects to change. This will allow your scripts to work right away.
https://github.com/philip/MySQLConverterTool
It's a forked version of the Oracle original version, and it's kosher.
That said, it's not too difficult to update your code, and you might want to migrate to an object orientated methodology anyway ...
1) The Connection
For all intents and purposes, you need a new connection function that saves the connection as a PHP variable, for example;
$mysqli = new mysqli($host, $username, $password, $database);
Notice I've saved the connection to $mysqli. You can save to $db or whatever you like, but you should use this throughout your code to reference the connection.
Remember to enable error reporting for mysqli before opening the connection;
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
2) The Query
Note: You should protect against SQL injection with prepared statements, which are available in MySQLi. Take a look at How can I prevent SQL injection in PHP?, but I'm just going to cover the basics here.
You now have to include the connection as an argument in your query, and other mysqli_ functions. In procedural code it's the first argument, in OO you write it like a class method.
Procedural:
$result = mysqli_query($mysqli, $sql);
OO:
$result = $mysqli->query($sql);
3) Fetch Result
The fetching of the result is similar to the old mysql_ function in procedural;
while ($row = mysqli_fetch_assoc($result))
but as $result is now an object in mysqli, you can use the object function call;
while ($row = $result->fetch_assoc())
4) Close Connection
So as before, you need to include the connection in the close function; as an argument in procedural;
mysqli_close($mysqli);
and as the object that you run the function on in OO;
$mysqli->close();
I would be here forever if I went through them all, but you get the idea. Take a look at the documentation for more information. Don't forget to convert any connection close, result release, or error and row counting functions you have.
The basic rule of thumb is for functions that use the database connection, you need to include it in the function now (either as the first argument in procedural, or the object you use to call the function in OO), or for a result set you can just change the function to mysqli_ or use the result set as the object.
If you cannot convert all calls to the mysqli functions on a old project, you could install and include the library php7-mysql-shim.
It will try to create a transparent replacement for mysql on PHP 7 using mysqli.
Obviously the performance is slower, but it's a solution to get around the problem in a couple of minutes.
You may safely include the library in projects working with PHP 5.6 (it will be ignored).
if (defined('PHP_VERSION_ID') && (PHP_VERSION_ID >= 50600)) { require_once "mysql-shim.php"; }
You can't. some of the functions of mysql and mysqli require different parameters. So you should know which will use the same parameters.
Related
Connection file is as below
$host="localhost";
$username="root";
$password="123";
$database = "order";
$con = mysqli_connect($host, $username, $password, $database);
$sel_db=mysqli_select_db($con,$database) or die("Cannot Select Database");
In each file I include above connection file
My older code for mysql is like
mysql_query("select * from order_detail");
and new query for mysqli is as below
mysqli_query($con,"select * from order_detail");
Above query required $con for connection
and mysql_fetch_array($var) becomes mysqli_fetch_array($var) it does not required $con
mysql_real_escape_string($var) becomes mysql_real_escape_string($con,$var);
So my question is that which query required $con as connection
The mysql functions implicitly used the last connection that was made if no connection was explicitly given. Note that you already could pass in a connection, even to the old function as you can read here. This behavior is confusing and error prone, so fortunately they made that more explicit in the mysqli functions.
I'm not sure that is the main reason though. It probably might have more to do with the fact that mysqli also has an object syntax, and that one syntax wraps another. The $con variable in the procedural version and the object instance in the objective version both serve the same purpose: telling the function/method which connection to use. Actually, the doc says that the connection parameter for mysqli_query is a mysqli object instance, so mysqli_query might just be implemented like this as a wrapper function to make it easier to convert your code from mysql to mysqli:
function mysqli_query($link, $query, $resultmode = MYSQLI_STORE_RESULT) {
return $link->query($query, $resultmode);
}
If you didn't understand anything I said in this last paragraph, don't worry, it's not really important. ;)
Anyway, while mysql_query performs a query on a connection, mysql_fetch_array fetches values from a query result. The $var your pass to it already contains all the information it needs. It doesn't need a connection at that point, so there is no need to pass it as an argument. There is no mysqli_fetch_array by the way. Instead you should use mysqli_stmt_fetch, to which the same applies: it doesn't need a connection, but a statement object (mysqli_stmt), which represents the query result.
Many of the mysqli functions have the same or similar parameters as their predecessors, but there may be differences. So for every function you use, I'd check the official documentation.
And also, I'd use an IDE or editor that will help you with the function syntax by providing built in code insight. Netbeans for PHP is a quite elaborate one that can be used for free, but there are even better ones (like PHPStorm) if you can spend some money.
PS: If you use prepared statements, you can get rid of mysql_real_escape_string completely.
I'm updating a site from MySQL to MySQLi, using OOP.
For the most part things are going well, but this line is giving me divine trouble:
$pager_total = mysql_num_rows(mysql_query($MySQLctr,$MyDB));
I've tried
$pager_total = $MyDB->query($MySQLctr)->num_rows;
and
$pager_total = ($MyDB->query($MySQLctr))->num_rows;
and
$new_object = $MyDB->query($MySQLctr);
$pager_total = $new_object->num_rows;
but no avail.
Any thoughts?
OOP mysqli is very simple :) try this example
$DBH=new mysql('location of database','username','password','database');
$get=$DBH->prepare('SELECT COUNT(*) FROM table');//notice the count(*) in the query, it's not the same as mysql_num_row() but works in the same way
//prepare is also a more secure way of processing query, please look up the difference between prepare and query though.
//$DBH->prepare('SELECT * FROM table WHERE ID=2'); will not work.
$get->execute();//execute the above prepared statement
$get->bind_result($count);//get the result of the query, should be whatever COUNT(*) returns
$get->close();//don't forget to close your connection
The mysqli of mysql_num_row() is $query->num_rows().
I added a little bit extra to get you started with OOP mysqli :)
Notice though that I didn't use $get->num_rows() but COUNT(*) instead for a more simple example. Here is another method you may be more familiar with:
$counter=$DBH->query('SELECT * FROM table');
echo$counter->num_rows();
Also see here for more examples.
Thank you for your help everyone. It turns out that the db connection was being closed prematurely by one of the included files. I've noticed, during this project where I'm transitioning the code from procedural MySql to OOP MySQLi that the db closures didn't affect the functionality of the site before, but definitely do once OOP MySqli is in place. I'm curious why.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
mysql_escape_string VS mysql_real_escape_string
I need to get company_name (given by user through a form) entered into my mysql database.
When I use
$company = mysqli_real_escape_string($_POST['company_name'])
I get an error
Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given in /opt/lampp/htdocs/Abacus-Version-2/admin/Company/insert_company.php on line 58
But everything seems to fine while using
$company = mysql_real_escape_string($_POST['company_name'])
What can I do in such cases?
The one to use depends on whether you are using the MySQLi extension or the MySQL extension
// procedural mysqli
$db = new mysqli;
$sql = sprintf("INSERT INTO table (id,name,email,comment) VALUES (NULL,'%s','%s','%s')",
mysqli_real_escape_string($db,$name),
mysqli_real_escape_string($db,$email),
mysqli_real_escape_string($db,$comment) );
// mysql
$conn = mysql_connect();
$sql = sprintf("INSERT INTO table (id,name,email,comment) VALUES (NULL,'%s','%s','%s')",
mysql_real_escape_string($name,$conn),
mysql_real_escape_string($email,$conn),
mysql_real_escape_string($comment,$conn) );
mysql_real_escape_string() is designed to make data safe for insertion into the database without errors. (IE such as escaping slashes so that it doesn't break your code).
You should use mysql_ or mysqli_ functions to match your connection string. "mysqli" is the object oriented implementation of the mysql set of functions, so the functions are called in the object oriented style. "mysql" is procedural. I'd suggest changing over to "mysqli" because I believe there has been talk of depreciating the "mysql" functions in future versions.
If you connection string is:
mysql_connect()
then use:
mysql_real_escape_string($_POST[''])
If it is:
$mysqli = new mysqli();
then use:
$mysqli->real_escape_string($_POST[''])
Definitely NO
Both functions has nothing to do with form data.
They have to be used to format string literals inserted into SQL query only.
This function belongs to the SQL query, not to whatever form. And even to very limited part of the query - a string literal.
So, every time you're going to insert into query a string literal (frankly, a portion of data enclosed in quotes), this function ought to be used unconditionally.
For the any other case it shouldn't be used at all.
As for the error you're getting - it's pretty self-explanatory: this function expects 2 parameters, not one. Just pass proper parameters as stated in the manual page for this function, and you'll be okay
It should be this if you use Procedural style:
$city = mysqli_real_escape_string($link, $city);
where link is the connection
or this when you use Object oriented style:
$city = $mysqli->real_escape_string($city);
Check out the php manual:
http://php.net/manual/en/mysqli.real-escape-string.php
Since all the MySQL extension is being deprecated, you'd best use the MySQLi methods instead, it's more future proof.
Both variants are fine* (Please look at my Update).
When you are using a mysql_connect then you should stick to mysql_real_escape_string() and also pass the connection handle.
When you are using a mysqli_connect then you should stick to mysqli_real_escape_string().
UPDATE
As pointed out by Jeffrey in the comments, using mysql_ functions is NOT fine. I agree to that. I was just pointing out, that you need to use the function that is used by the MySQL-extension you are using.
It came to me, that it was not the question, which MySQL-extension to use, but which function for escaping data.
If you ask me:
Use mysqli or PDO, because mysql is not recommendable and deprecated.
Pass the Connection Handle to the escape-function or better
use prepared Statements (PDO-Style)
$result = $myDB->Execute($query) or die(GetDbError($myDB->ErrorMsg()));
Lets say i wanna remove adodb form my script:
$result = $myDB->mysql_fetch_assoc($query) or die(GetDbError($myDB->ErrorMsg()));
It would be correct or not ?
No, it's not correct - mysql_fetch_assoc is a function, not a method - and you would not even have a $myDB object.
I'd also suggest using PDO instead of the plain mysql/mysqli functions.
If $myDB is an adodb object, then $result is an ADORecordSet object. You should fetch (or getAssoc()) on that $result. You're using adodb in order to avoid developing PHP code in a more abstract way, without using particular database engine functions. Then, if you need to move to another database system, you'll need to make minor changes to statements.
$array = $result->FetchRow();
Should I use php PDO or normal mysql_connect to execute database queries in PHP?
Which one is faster?
One of the big benefits of PDO is that the interface is consistent across multiple databases.
There are some cool functions for prepared statements too, which take some of the hassle out of escaping all your query strings. The portability of PDO is greater than mysql_connect.
So, should I use PDO for those reasons or stick to the traditional mysql_connect?
PDO is a bit slower than the mysql_*
But it has great portability. PDO provides single interface across multiple databases. That means you can use multiple DB without using mysql_query for mysql, mssql_query for MS sql etc. Just use something like $db->query("INSERT INTO...") always. No matter what DB driver you are using.
So, for larger or portable project PDO is preferable. Even zend framework use PDO.
Some quick timings indicate PDO is slightly faster at connecting.
$start = microtime(true);
for($i=0; $i<10000; ++$i) {
try {
$db = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage()."\n";
}
$db = null;
}
$pdotime = microtime(true) - $start;
echo "PDO time: ".$pdotime."\n";
$start = microtime(true);
for($i=0; $i<10000; ++$i) {
$db = mysql_connect($host, $user, $password);
if(!$db) {
echo "Connection failed\n";
}
if(!mysql_select_db($schema, $db)) {
echo "Error: ".mysql_error()."\n";
}
mysql_close($db);
}
$rawtime = microtime(true) - $start;
echo "Raw time: ".$rawtime."\n";
Gives results like
PDO time: 0.77983117103577
Raw time: 0.8918719291687
PDO time: 0.7866849899292
Raw time: 0.8954758644104
PDO time: 0.77420806884766
Raw time: 0.90708494186401
PDO time: 0.77484893798828
Raw time: 0.90069103240967
The speed difference will be negligible anyway; establishing a network connection will likely take a LOT longer than any overhead incurred by PDO, especially if the mysql server is on another host.
You mentioned all the reasons to use PDO yourself. Really, never use the mysql_* functions directly, either use PDO, or use some other library.
With PDO you can uses binded params and that will prevent most sql injection attacks.
You can gain more speed using PDO prepared statements.
standard interface to all db backends
There are a bunch of useful methods (like the fetch* family)
I don't think speed is what people are looking for when they are using PDO -- I don't know if there is a difference, and I honnestly don't care : as long as I'm doing a couple of queries to a database when generating a page, a couple of milliseconds on the PHP side will not change anything.
There are two/three great things with PDO, compared to mysql_* :
More or less constant interface accross databases ; better than using mysql_*, pg_*, oci_*, ...
Object-Oriented API (mysqli_* has an OO-API, but not mysql_*)
Support new features of MySQL >= 4.1 (same as mysqli_*, but not mysql_*, again)
BTW : I'm generally using PDO -- either "by hand", or as it's integrated in / used by Zend Framework and/or Doctrine.
As a sidenote : Even if you are not going to use PDO, note that using mysqli instead of mysql is recommended.
See this page of the PHP manual, about that.
I did some performance testing to compare Mysqli functions to PDO functions using both prepared statements and regular direct queries (tested using select statements on Mysqlnd and MyISAM tables).
I found that PDO queries are just slightly slower than Mysqli, but only slightly. This makes sense since PDO used for this purpose mostly just a wrapper that calls Mysqli functions. The advantage to using PDO is that it makes it a little easier to migrate to a different database because the function names aren't specific to MySQL.
The real performance difference is in whether you use prepared queries. There is a large and significant performance penalty to using prepared queries. Other people who have tested them have found the same results.
The only time prepared queries are faster is if you are preparing a query once and then submitting it thousands of times with different data values. Otherwise, it's always faster to use mysqli::query() or PDO::query(). But it's important to be aware that those functions don't escape data values for you, so you need to remember to use mysqli::real_ escape_ string() or PDO::quote() on data variables.
I would generally recommend using PDO unless there is a specific reason you cannot. If there is no little difference between the two and you have no reason not to use PDO, I believe it would be better to get into the practice of using DB abstraction in your applications than going with mysql_* simply because it is there. I would say let best practice win.
In both cases, you call the same mySQL server from the same Php server ... so you cannot notice a lot of difference.
If you want good performance, think about cache (memcache or simple Php file ...) and make a good data base structure (INDEX ...)
PDO is better than SQl
PDO And His Prepare Statement Provide Best Secure Code against SQL injection
PDO is Object Oriented ;)
PDO is compatible with some Databases Engine As Explained Before
MySQLl_* Is Deprecated and will be removed soon
PDO provide more functionality with less line of codes Example:
Pdo
Connect
Check for "<" And ">" And "#" (This check for global uses)
Prepare
Execute
Close
MySQL_*
Connect
Add Backslash
Xsafe
Check for "<" And ">" And "#" (This check for global uses)
Query
Close
both the same functionality but you compare for codes
PDO is more Humanly Readable :)
So what you think?
If performance isn't a "real problem" for you, you should use PDO. The performance differs by small margins, and PDO has a very nice and portable cross-database interface wich can save you some headaches in case you need to use several database drivers.
The mysql_connect function is deprecated as of PHP 5.5.0 and, as with most deprecated features, will be removed. Therefore, prefer using PDO_MySQL (or another alternative MySQLi ) over mysql_connect.
Source: http://php.net/manual/en/function.mysql-connect.php
Some Advantages of PDO:
Can Access multiple database.
Provided many database driver to connect with different different database.
When you switch from one database to another database, you need not to write all the code to connect with new database, just change the connection string and some query which are required for new database.
It provides prepare statement which is a kind of template of query which compiled only once and can be executed as many times as you want, by just changing the attributes which is called place-holder.
Easy and efficient General Operation like- Insert, update...etc.
PDO database connection code:
<?php
$dbhost = 'localhost';
$dbname = 'clsrepair';
$dbuser = 'root';
$dbpass = '';
try {
$db = new PDO("mysql:host={$dbhost};dbname={$dbname}",$dbuser,$dbpass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Connection error: ".$e->getMessage();
}
?>
Normal MySQL database connection code:
<?php
mysql_connect("localhost","root", "");
mysql_select_db ("clsrepair");
?>
or
<?php
$dbHost = 'localhost'; // usually localhost
$dbUsername = 'root';
$dbPassword = '';
$dbDatabase = 'clsrepair';
$db = mysql_connect($dbHost, $dbUsername, $dbPassword) or die ("Unable to connect to Database Server.");
mysql_select_db ($dbDatabase, $db) or die ("Could not select database.");
?>
MySQL database connection code easy but PDO has many advantage.