I’m using the following PHP MySQL database class. I’m curious as to what I could do to make it more secure. I’m happy with it so far, but without suggesting to “use PDO” what can I do to improve this currently?
<?
class DbConnector {
public static function getInstance(){
static $instance = null;
if($instance === null){
$instance = new DbConnector();
}
return $instance;
}
var $theQuery;
var $link;
function DbConnector() {
$host = 'localhost';
$db = '';
$user = '';
$pass = '';
// connect to the db
$this->link = mysql_connect($host, $user, $pass);
mysql_select_db($db);
register_shutdown_function(array(&$this, 'close'));
}
function find($query) {
$ret = mysql_query($query, $this->link);
if (mysql_num_rows($ret) == 0)
return array();
$retArray = array();
while ($row = mysql_fetch_array($ret))
$retArray[] = $row;
return $retArray;
}
function insert($query) {
$ret = mysql_query($query, $this->link);
if (mysql_affected_rows() < 1)
return false;
return true;
}
function query($query) {
$this->theQuery = $query;
return mysql_query($query, $this->link);
}
function fetchArray($result) {
return mysql_fetch_array($result);
}
function close() {
mysql_close($this->link);
}
function exists($query) {
$ret = mysql_query($query, $this->link);
if (mysql_num_rows($ret) == 0)
return false;
}
function last_id($query) {
return mysql_insert_id($query);
}
}
?>
If you don’t want to use something that would automatically escape strings for you, you should at least provide an
escapeString($string)method (which would callmysql_real_escape_string()) that you can use to escape strings when composing the query.If you want to start using PDO (highly recommended) then you will probably have different methods and won’t need to include an escaping method.
As for general considerations:
var, but rather usepublic,protectedorprivate(varhas been deprecated as of PHP 5.0, and is currently an alias forpublic)__construct()method is preferred instead of the method with the name of the classmysql_connect()andmysql_select_db()will returnfalseif they cannot do what they’re supposed to; you should throw an exception if that happens and catch it where you use the classmysql_query()call in thefind()andexists()methods might return something other than a resource (falsefor example) so you should check for that before callingmysql_num_rows()$theQueryat all, you should remove it$theQuery, you should make it private and provide agetQuery()accssor method$linkproperty to the resource returned bymysql_connect(), you should use that property in all yourmysql_*calls, such as the one atlast_id()$linkprivate (as a rule of thumb, all properties should be private or protected, and accessor methods should be provided when needed – read about the concept of encapsulation)public, having an explicitpublickeyword before each of them will make things clearer