Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use MySQLi Prepared Statements with Stored Procedures

I'm trying to learn more about MySQL and how to protect against SQL injections so my research has brought me to Prepared Statements which seems to be the way to go.

I'm also working on learning how to write Stored Procedures and am now trying to combine the two. There isn't much info on this though.

At the moment in my PHP test app I have a function that calls an SP with a normal MySQL command like this:

mysql_query("CALL usp_inserturl('$longurl', '$short_url', '$source')");

How can I do the same with MySQLi and a Prepared Statement to make it as safe as possible to injections?

Thanks!

like image 867
Brigante Avatar asked Apr 04 '11 10:04

Brigante


People also ask

Can we use prepared statement for stored procedure?

We can use the prepared statements in a stored procedure by writing it inside the BEGIN and END block. We can understand it by creating an example that returns all records from a table by passing the table's name as a parameter of the stored procedure.

Which function is used in Mysqli with prepared statements?

$stmt->bind_param("sss", $firstname, $lastname, $email); This function binds the parameters to the SQL query and tells the database what the parameters are. The "sss" argument lists the types of data that the parameters are. The s character tells mysql that the parameter is a string.

Can we use prepared statement for select query in PHP?

You must always use prepared statements for any SQL query that would contain a PHP variable. To do so, always follow the below steps: Create a correct SQL SELECT statement.


1 Answers

Try the following:

$mysqli= new mysqli(... info ...); 
$query= "call YourSPWithParams(?,?,?)"; 
$stmt = $mysqli->prepare($query); 
$x = 1; $y = 10; $z = 14;
$stmt->bind_param("iii", $x, $y, $z); 
$stmt->execute(); 
like image 157
Ali Avatar answered Oct 10 '22 11:10

Ali