Possible Duplicate:
Do I need to escape data to protect against SQL injection when using bind_param() on MySQLi?
I have a class that simplifies doing a queries. Here is a code example how to insert data:
$dbi->prepare("INSERT INTO `temp` (`name`,`content`) VALUES (?,?);")->execute($name,$content);
There is a function in class like this:
public function execute(){
if(is_object($this->connection) && is_object($this->stmt)){
if(count($args = func_get_args()) > 0){
$types = array();
$params = array();
foreach($args as $arg){
$types[] = is_int($arg) ? 'i' : (is_float($arg) ? 'd' : 's');
$params[] = $arg;
/*
or maybe $params[] = $this->connection->real_escape_string($arg);
*/
}
array_unshift($params, implode($types));
call_user_func_array(
array($this->stmt, 'bind_param'),
$this->_pass_by_reference($params)
);
}
if($this->stmt->execute()){
$this->affected_rows = $this->stmt->affected_rows;
return $this;
}
else {
throw new Exception;
}
}
else {
throw new Exception;
}
}
When I declare $params[]
I have like this $params[] = $arg;
Should I put $params[] = $this->connection->real_escape_string($arg);
or not?
Thanks.
According to PHP Manual on mysqli
and prepared statements:
Escaping and SQL injection
Bound variables will be escaped automatically by the server. The server inserts their escaped values at the appropriate places into the statement template before execution. A hint must be provided to the server for the type of bound variable, to create an appropriate conversion. See the mysqli_stmt_bind_param() function for more information.
The automatic escaping of values within the server is sometimes considered a security feature to prevent SQL injection. The same degree of security can be achieved with non-prepared statements, if input values are escaped correctly.
So no, you don't have to take care about escaping, server will take care about escaping for you.
Escaping manually will result in double escaped values. And in my personal opinion the greatest advantage of placeholders ?
in sql statements is that you don't have to take care about escaping.
No. When you use parameters, you don't need to escape the strings.
In fact, you must not escape the strings, because you'll end up storing strings in your database containing literal backslashes. This is not what you want.