I built my own simple prepared statements section in this stripped down (but should be functional) class. Do you think it is a simple and effective implementation? Any ideas for improvements?
class MyClass {
public function __construct(array $init){
$this->_info['host'] = $init['host'];
$this->_info['user'] = $init['user'];
$this->_info['pass'] = $init['pass'];
$this->_info['db'] = $init['db'];
$this->getConnection();
}
public function getConnection(){
if($this->_link === NULL)
$this->_link = mysql_connect($this->_info['host'], $this->_info['user'], $this->_info['pass']);
if(!$this->_link)
throw new Exception('Database connection failure');
if(!mysql_select_db($this->_info['db'], $this->_link))
throw new Exception('Database selection error');
return $this;
}
/**
* Function to replicate mysql_real_escape_string
*
* @param string $text
* @return string
*/
protected static function clean($text){
$replace = array(
"\x00" => '\x00',
"\n" => '\n',
"\r" => '\r',
'\\' => '\\\\',
"'" => "\'",
'"' => '\"',
"\x1a" => '\x1a'
);
return strtr($text, $replace);
}
protected function prepare($sql, array $data = array()){
$data = array_map(array('MyClass', 'clean'), $data);
$numToReplace = substr_count($sql, '?');
for($i = 0; $i < $numToReplace; $i++){
$sql = preg_replace("#\?#", $data[$i], $sql, 1);
}
return $sql;
}
public function query($sql, array $data = array()){
$q = mysql_query($this->prepare($sql, $data), $this->_link);
if(!$q)
return mysql_error($this->_link);
return $q;
}
public function row($sql, array $data = array()){
$q = $this->query($sql, $data); // query resource
return mysql_fetch_assoc($q);
}
public function rows($sql, array $data = array()){
$q = $this->query($sql, $data); // query resource
$d = array(); // data holder
while(($r = mysql_fetch_assoc($q)) !== FALSE)
$d[] = $r;
return $d;
}
}
$class = new MyClass($db_init);
$results = $class->rows("SELECT `something FROM `table` WHERE `id` = '?' AND `id2` = '?'", array($id, $id2));
echo '<pre>' . print_r($results, true) . '</pre>';
Your thoughts?