Reputation: 634
I'm working on a PHP project with mysqli and need to retrieve the info from the user via $_POST
, my problem is that I want to use prepared statements and mysqli->real_escape_string
like this:
//$mysqli is the link to my database
if( isset($_POST['ID_name']) && isset($_POST['Nombre_name']) )
{
//just in case magic_quotes_gpc is on
$id = trim(htmlentities(mysqli_real_escape_string(stripslashes($mysqli,$_POST['ID_name']))));
$nombre = trim(htmlentities(mysqli_real_escape_string(stripslashes($mysqli,$_POST['Nombre_name'])));
//... more code validation but not reffered to my question...
$query="insert into empleado_php values(?,?)";
if(!($consulta=$mysqli->stmt_init())){
echo"Error al crear la sentencia ingresar.php";
exit();
}
if(!($consulta->prepare($query))){
echo"Error al prepara la consulta ingresar.php";
exit();
}
if(!($consulta->bind_param("ss", $id, $nombre))){
echo"Error anexando parametros ingresar.php";
exit();
}
if(!($consulta->execute())){
echo "Error al ejecutar la consulta";
echo"<br>";
echo "Error ".$consulta->error. "con codigo " .$consulta->errno;
exit();
}
else{
echo "Datos ingresados exitosamente !!!";
}
$consulta->close();
$mysqli->close();
?>
My question is: do I need to use mysqli_real_scape_string
when using prepared statement? if yes, my code is good? could you give a better sample?
Upvotes: 0
Views: 504
Reputation:
From http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
Escaping and SQL injection Bound variables are sent to the server separately from the query and thus cannot interfere with it. The server uses these values directly at the point of execution, after the statement template is parsed. Bound parameters do not need to be escaped as they are never substituted into the query string directly. 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.
Upvotes: 1