what is the best way to call data from MySQL with speed and security in mind?
can some one provided some suggestions开发者_开发百科 of constructing MySQL querys that are both fast as well as secure.
Currently I am using typical MySQL calling method
$q = ("...");
$r = mysql_query($q);
but I was looking into OOP database programming so I am wondering which method would be the best to use and implemend on multiple pages with security and speed in mind.
The best way without much effort would be to use PHP PDO [PHP Data Object] extension. Here is the manual for it:
http://php.net/manual/en/book.pdo.php
Example:
<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindParam(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();
?>
You should learn the idea of "prepared statements" - it really improves security compared to mysql_query() way.
For security purposes, always use database parameters instead of putting what the user provides directly in the query. You can do this by either using the mysqli_ family of functions or the PDO object.
For speed, you should just try to optimize your queries as much as possible as well as try to do as few queries as needed because each hit to the database will slow down your application.
The mysqlnd
library included in PHP >= 5.3 is faster than the original mysql
and mysqli
libraries.
Security is a much bigger ball of wax, but the general principle to keep in mind is not to ever trust or assume that user-generated data is safe. Use the string escape functions on strings; make sure things you expect to be ints or floats are typecasted as such.
It is hard to combine most important features in one think in general, PDO provide data-access abstraction layer, so you write once and use your script with different database server's, however, PDO not mush faster then MySQLi as the benchmark here show, but its provide many other features, query cache, prepared statement, and support most known databases server.
If you really looking for OOP database abstraction layer then use PDO, easy to use, fast to learn.
精彩评论