PHP PDO vs normal mysql_connect - php

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.

Related

How do I query MSSQL then display the result using php? [duplicate]

There is a range of mssql_* Which are not in the depreciation process.
They work the same as mysql_* functions; they need to me manually escaped, please find the link to the manual below:
http://uk1.php.net/manual/en/book.mssql.php
MSSQL_* Functions was apart of php5-mssql but have now been moved into php5-sybase
Furthermore, using PDO for your Database Construct, is available but is experimental
http://php.net/manual/en/ref.pdo-dblib.php
But my overall question, from the fact that PDO/MySQLI is being pushed as main database communication solution, should I stop using the functions mssql_*
Or is it possible for:
PDO Connection:
$dsn = 'mssql:host=localhost;dbname=testdb';
$user = 'dbuser';
$password = 'dbpass';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
But if this process is still listed as experimental, should developers using Microsoft SQL Server for their databases, wait till this extension is stable for MSSQL Servers
So at the end of the day, PDO Extension or MSSQL_* Functions even though they are not depreciated.. If so, why?
My Own Opinion
I have been using PDO to connect to a MSSQL database for over a year now and so far I have found absolutely no issues.
In fact, I looked into using the mssql_* functions before migrating to PDO, and came to the conclusion that they were a much less reliable, not to mention, insecure way of connecting to a MSSQL Database.
Logically
From a logical point of view, PDO is also the better option as it only takes a few tweaks to the code in order to change from MSSQL to MySQL.
I wrote a wrapper class for the PDO class that makes connecting to these databases very easy.
Consider this as an example:
<?php
// +------------------------------------------------------------------------+
// | class.mssql.php |
// +------------------------------------------------------------------------+
// | Copyright (c) Company Ltd 2013. All rights reserved. |
// | Version 1.0 |
// | Last modified 30/01/2013 |
// | Email email#company.co.uk |
// | Web http://www.company.co.uk |
// +------------------------------------------------------------------------+
// Make sure the SQL class is included
require_once("class.sql.php");
/*
* Class mssql
*
* #version 1.0
* #author Ben Carey <email#company.co.uk>
* #copyright Company Ltd
*
*/
class mssql extends sql{
/**
* Initialize the object and set/reset all variables
*
* This function is called when the object is constructed
*
* #access private
*/
function __construct(&$memcache){
// Call the sql construct
parent::__construct($memcache);
// Global MsSQL defaults
$this->query_escaper_left = "[";
$this->query_escaper_right = "]";
$this->connection_engine = "sqlsrv";
$this->connection_parameter_host = "server";
$this->connection_parameter_database = "Database";
$this->select_db_function = "db_name()";
}
}
?>
Anything that is unique to MSSQL is defined in this extension and then passed up to the parent class class.sql.php. The beauty of PDO is that the code in the file class.sql.php does not have to be altered in any way to work with any database (or, all the databases that I have tried thus far).
So all that is needed here is a small extension for each database type and it will work.
Whereas, with the native mssql_* functions, if you were to decide to change database for any particular reason, you would have to rewrite everything. Not to mention, you would have to use PDO for MySQL anyway given that the mysql_* functions are now deprecated.
My Testing with PDO
I have been running complex stored procedures, with INPUT PARAMETERS, OUTPUT PARAMETERS, INOUT PARAMETERS, on databases with 100,000,000+ records in them. These have worked absolutely flawlessly, and continue to do so!
References
Another reason not to use the mssql_* functions is that they are no longer supported on Windows with PHP version 5.3 or later:
See Here
The SyBase Extension falls under the same category as the mssql_* functions. They are procedural, impractical and not portable at all!
Functionality
At a glance, I have noticed that none of these extensions have a function equivalent to the mysql_real_escape_string() function. Whereas, in PDO, there is no need for this
Conclusion
It goes without saying that I am a moral PDO supporter (and this has only come after using it for 1 year!). That is not to say I will not listen to other peoples opinions on the mssql_* functions, it will just be very hard to persuade me, and I think most people, that these functions can even compete the PDO.
So to conclude, in my opinion, PDO is the way forward for the following key reasons:
It is very portable, easy to switch to different databases with minimal code
It is secure without the need of functions like mysql_real_escape_string()
It is fast becoming the norm for developers
If you do not have experience with Object Oriented Programming, then it is an excellent introduction
It comes pre-installed with most PHP Packages
It can execute comples queries with ease, including stored procedures
After benchmarking it with a MySQL database against the old deprecated mysql_* functions, it has proved to be faster in a lot of cases, if not all cases. - See Here
I asked a similar question a while back, and the same conclusion was drawn:
See here
This could spark up a good debate. I guess the only way to test the stability of the PDO functions towards Microsoft SQL Servers, is to setup your own local testing zone and push the PDO Class to its abilities.
As you said, php5-sybase contains MSSQL Functions and are not in the deprecation process.
I guess it's down to what the developer feels comfortable with.
If you're happy with MSSQL_* Functions, then go ahead and use them, but there could be a possibility they will end up getting deprecated from PHP altogether in the near future -- it's happening with MySQL Functions.
Although, if you're looking for a change and new challenges, with added security from SQL Injection, then go ahead and try out the PDO compatibility with MSSQL Servers.
It's entirely down to you.
From my preference & and guess many other developers preference, I would say go for the PDO functions. I assume it would work as normal.
<?php
$dsn = 'mssql:host=localhost;dbname=testdb';
$user = 'dbuser';
$password = 'dbpass';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$Query = $dbh->prepare("SELECT * FROM Tbl WHERE `ID` = :id");
$Query ->bindParam(':id', $ID, PDO::PARAM_INT);
$Query->execute();
// etc..
?>
PDO is definitely the way to go and for linux users I stongly recommend going with the sybase connector and the the dblib DSN.
For ubuntu users with PHP7 it would be:
sudo apt-get install php-sybase freetds-common libsybdb5
And for connecting:
$db = new PDO("dblib: host=$hostname:$port; dbname=$dbname", $dbuser, $dbpassword);
And you should be good to go.
PDO is the obvious choice with security in mind. PDO code is portable - it can be adjusted to send information to a number of databases without having to change the function calls and only changing a few parameters.
The MSSQL class is not portable the way that PDO is portable.
PDO has excellent support for prepared statements while MSSQL has none.
PDO acts as an abstraction layer much like JDBC in Java and is portable.
PDO has support for transactions, is better for handling errors
Hope the answer is obvious!

Can I blindly replace all mysql_ functions with mysqli_?

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.

What is the PDO equivalent of function mysql_real_escape_string?

I am modifying my code from using mysql_* to PDO. In my code I had mysql_real_escape_string(). What is the equivalent of this in PDO?
Well No, there is none!
Technically there is PDO::quote() but it is rarely ever used and is not the equivalent of mysql_real_escape_string()
That's right! If you are already using PDO the proper way as documented using prepared statements, then it will protect you from MySQL injection.
# Example:
Below is an example of a safe database query using prepared statements (pdo)
try {
// first connect to database with the PDO object.
$db = new \PDO("mysql:host=localhost;dbname=xxx;charset=utf8", "xxx", "xxx", [
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);
} catch(\PDOException $e){
// if connection fails, show PDO error.
echo "Error connecting to mysql: " . $e->getMessage();
}
And, now assuming the connection is established, you can execute your query like this.
if($_POST && isset($_POST['color'])){
// preparing a statement
$stmt = $db->prepare("SELECT id, name, color FROM Cars WHERE color = ?");
// execute/run the statement.
$stmt->execute(array($_POST['color']));
// fetch the result.
$cars = $stmt->fetchAll(\PDO::FETCH_ASSOC);
var_dump($cars);
}
Now, as you can probably tell, I haven't used anything to escape/sanitize the value of $_POST["color"]. And this code is secure from myql-injection thanks to PDO and the power of prepared statements.
It is worth noting that you should pass a charset=utf8 as attribute, in your DSN as seen above, for security reasons, and always enable
PDO to show errors in the form of exceptions.
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
so errors from you database queries won't reveal sensitive data like your directory structure, database username etc.
Last but not least, there are moments when you should not trust PDO 100%, and will be bound to take some extra measures to prevent sql injection, one of those cases is, if you are using an outdated versions of mysql [ mysql =< 5.3.6 ] as described in this answer
But, using prepared statements as shown above will always be safer, than using any of the functions that start with mysql_
Good reads
PDO Tutorial for MySQL Developers
There is none*! The object of PDO is that you don’t have to escape anything; you just send it as data. For example:
$query = $link->prepare('SELECT * FROM users WHERE username = :name LIMIT 1;');
$query->execute([':name' => $username]); # No need to escape it!
As opposed to:
$safe_username = mysql_real_escape_string($username);
mysql_query("SELECT * FROM users WHERE username = '$safe_username' LIMIT 1;");
* Well, there is one, as Michael Berkowski said! But there are better ways.
$v = '"'.mysql_real_escape_string($v).'"';
is the equivalent of $v = $this->db->quote($v);
be sure you have a PDO instance in $this->db so you can call the pdo method quote()
There is no need of mysql_real_escape_string in PDO.
PDO itself adjust special character in mysql query ,you only need to pass anonymous parameter and bind it run time.like this
Suppose you have user table with attribute name,email and password and you have to insert into this use prepare statement like this
you can pass name as => $name="Rajes'h ";
it should execute there is no need of equivalent of mysql_real_escape_string
$stmt="INSERT into user(name,email,password) VALUES(:name,:email,:password)";
try{
$pstmt=$dbh->prepare($stmt);//$dbh database handler for executing mysql query
$pstmt->bindParam(':name',$name,PDO::PARAM_STR);
$pstmt->bindParam(':email',$email,PDO::PARAM_STR);
$pstmt->bindParam(':password',$password,PDO::PARAM_STR);
$status=$pstmt->execute();
if($status){
//next line of code
}
}catch(PDOException $pdo){
echo $pdo->getMessage();
}
The simplest solution I've found for porting to PDO is the replacement for mysql_real_escape_string() given at https://www.php.net/manual/en/mysqli.real-escape-string.php#121402. This is by no means perfect, but it gets legacy code running with PDO quickly.
#samayo pointed out that PDO::quote() is similar but not equivalent to mysql_real_escape_string(), and I thought it might be preferred to a self-maintained escape function, but because quote() adds quotes around the string it is not a drop in replacement for mysql_real_escape_string(); using it would require more extensive changes.
In response to a lot of people's comments on here, but I can't comment directly yet (not reached 50 points), there ARE ACTUALLY needs to use the $dbh->quote($value) EVEN when using PDO and they are perfectly justifiable reasons...
If you are looping through many records building a "BULK INSERT" command, (I usually restart on 1000 records) due to exploiting InnoDb tables in MySQL/Maria Db. Creating individual insert commands using prepared statements is neat, but highly inefficient when doing bulk tasks!
PDO can't yet deal with dynamic IN(...) structures, so when you are building a list of IN strings from a list of user variables, YOU WILL NEED TO $dbh->quote($value) each value in the list!
So yes, there is a need for $dbh->quote($value) when using PDO and is probably WHY the command is available in the first place.
PS, you still don't need to put quotes around the command, the $dbh->quote($value) command also does that for you.
Out.
If to answer the original question, then this is the PDO equivalent for mysql_real_escape_string:
function my_real_escape_string($value, $connection) {
/*
// this fails on: value="hello'";
return trim ($connection->quote($value), "'");
*/
return substr($connection->quote($value), 1, -1);
}
btw, the mysqli equivalent is:
function my_real_escape_string($value, $connection) {
return mysqli_real_escape_string($connection, $value);
}

which is the best mysql connection method to use stored procedure in php?

There are three methods to connect to mysql from php. mysql_connect,mysqli,PDO.
Which is best one to use a stored procedure in my application?
Please guide me
mysqli is straightforwardly better than mysql. PDO has a lot of good things going for it. I have a codebase in which at the moment I use mysqli along with stored procedures, and I don't have any complaints.
PDO supports stored procedure calls. Good tutorial here
http://www.phpro.org/tutorials/Introduction-to-PHP-PDO.html
PHP PDO is the easiest way to go, it takes care of all the specifics.
http://php.net/manual/en/book.pdo.php
example:
$pdo = new PDO( <connection_data> );
$stat = $pdo->prepare('SELECT * FROM table WHERE id=?');
$ids = array(1,2,3);
foreach($ids as $id) {
$r = $stat->execute(array($id));
if($r===false) # something wrong
else while(($c = $stat->fetch())!==false) {
var_dump($c);
}
}
I think you should use pdo because it supports not only mysql but also several other databases like MSSQL, Oracle, IBM DB2, PostgreSQL etc. Here is a great tutorial on PDO.

The best way to connect MySQL database in PHP

MySQL connection in PHP can be established in two ways:
$mysql = new mysqli('localhost', 'user_name', 'password', 'database_name');
or
$link = mysqli_connect('localhost', 'user_name', 'password');
mysqli_set_charset($link, 'utf8');
mysqli_select_db($link, 'database_name');
Which one is the better and why?
Whichever one you prefer. I would go with the OOP Interface for consistency with the rest of my application, because that's how I use MySqli. Also, in my opinion, the OOP interface way is much cleaner (aesthetically, at least).
The best way to connect to MySQL database in PHP is using PDO driver. PDO offers you parameterized query that lets you avoid SQL injection easily, and other features you may love. It is ready to work with object-oriented programming, which is pretty cool.
PDO also can be used to connect to other kinds of SQL databases, like SQL Server, etc. You have to learn PDO (it's simple) and then you can connect to many kinds of SQL databases.
Connecting using the mysqli extension gives you the ability to use newer MySQL features such as transactional queries and parameterised queries which aren't available using the older mysql extension.
Have a look at http://www.php.net/manual/en/book.mysqli.php
Will you be dealing with more than one database? If so it might be a good idea not to set the database_name in the constructor. Otherwise, no problem. Other than the fact that you set the charset in the second one I don't think there's much of a difference.
if (!function_exists('mysqli_init') && !extension_loaded('mysqli')) {
// error: mysqli extension error
exit('...');
}
$connection = mysqli_init();
#mysqli_real_connect($connection, DBHOST,
DBUSER, DBPASS, DBNAME, DBPORT, NULL, MYSQLI_CLIENT_FOUND_ROWS);
if (mysqli_connect_errno() > 0) {
// error: connection error
echo mysqli_connect_error();
exit();
}
// Force UTF-8.
mysqli_query($connection, 'SET NAMES "utf8"');
This sample according to Drupal6
database.mysqli.inc
Both approaches are valid ways to use the mysqli extension. The first is the object-oriented interface and the second is the procedural interface. They are equivalent and it is simply a matter of preference. See the PHP mysqli documentation.

Categories