Brigante
Brigante

Reputation: 1991

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!

Upvotes: 8

Views: 9932

Answers (4)

sbrbot
sbrbot

Reputation: 6469

You can use both of them in the same time: just make preparation with stored procedure:

//prepare and bind SP's parameters with your variables only once
$stmt=$db->prepare("CALL MyStoredProc(?,?)");
$stmt->bind_param('is',$i,$name);

//then change binded variables and execute statement
for($i=1;$i<9;$i++)
{
  $name="Name".$i;
  $stmt->execute();
}

Bear in mind that you should do the preparation only once (not again for each execution), then execute it more times (just change parameter value before).

Upvotes: 2

Jon Black
Jon Black

Reputation: 16569

You might find the following answer of use:

MySql: Will using Prepared statements to call a stored procedure be any faster with .NET/Connector?

In addition:

GRANT execute permissions only so your application level user(s) can only CALL stored procedures. This way, your application user(s) can only interact with the database through your stored procedure API, they can not directly:

select, insert, delete, update, truncate, drop, describe, show etc. 

Doesn't get much safer than that. The only exception to this is if you've used dynamic sql in your stored procedures which I would avoid at all costs - or at least be aware of the dangers if you do so.

When building a database e.g. foo_db, I usually create two users. The first foo_dbo (database owner) is the user that owns the database and is granted full permissions (ALL) so they can create schema objects and manipulate data as they want. The second user foo_usr (application user) is only granted execute permisisons and is used from within my application code to access the database through the stored procedure API I have created.

grant all on foo_db.* to foo_dbo@localhost identified by 'pass';

grant execute on foo_db.* to foo_usr@localhost identified by 'pass';

Lastly you can improve your code example above by using mysql_real_escape_string:

Upvotes: 0

user2288580
user2288580

Reputation: 2258

This one was a bit tricky but I eventually figured out how to both use a stored procedure (using IN parameters) that uses a prepared statement and retrieve the data through PHP. This example uses PHP 7.4.6 and MySQL 8.0.21 Community edition.

Here is the Stored Procedure:

CREATE DEFINER=`root`@`loalhost` PROCEDURE `SP_ADMIN_SEARCH_PLEDGORS`(
    IN P_email VARCHAR(60),
    IN P_password_hash VARCHAR(255),
    IN P_filter_field VARCHAR(80),
    IN P_filter_value VARCHAR(255)
)
BEGIN
    #Takes admin credentials (first tow paramaters and searches the pledgors_table where field name (P_filter_field) is LIKE value (%P_filter_value%))
    DECLARE V_admin_id INT(11);
    BEGIN
        GET DIAGNOSTICS CONDITION 1 @ERRNO = MYSQL_ERRNO, @MESSAGE_TEXT = MESSAGE_TEXT;
        SELECT 'ERROR' AS STATUS, CONCAT('MySQL ERROR: ', @ERRNO, ': ', @MESSAGE_TEXT) AS MESSAGE;
    END;
    SELECT admin_id INTO V_admin_id FROM admin_table WHERE password_hash = P_password_hash AND email = P_email;
    IF ISNULL(V_admin_id) = 0 THEN    
        SET @statement = CONCAT('SELECT pledgor_id, email, address, post_code, phone, alt_phone, contact_name
        FROM pledgors_table
        WHERE ',P_filter_field, ' LIKE \'%', P_filter_value, '%\';');
        PREPARE stmnt FROM @statement;
        EXECUTE stmnt;
    ELSE
        SELECT 'ERROR' AS STATUS, 'Bad admin credentials' AS MESSAGE;
    END IF;
END

And here is the PHP script

query = 'CALL SP_ADMIN_SEARCH_PLEDGORS(\''.
strtolower($email).'\', \''.
$password_hash.'\', \''.
$filter_field.'\', \''.
$filter_value.'\');';

$errNo = 0;
//$myLink is a mysqli connection
if(mysqli_query($myLink, $query)) {
    do {
        if($result = mysqli_store_result($myLink)) {
            while($row = mysqli_fetch_assoc($result)) {
                $data[] = $row;
            }
            mysqli_free_result($result);
        }
    } while(mysqli_next_result($myLink));
}
else {
    $errNo = mysqli_errno($myLink);
}
mysqli_close($myLink);

Upvotes: 1

Ali
Ali

Reputation: 3676

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(); 

Upvotes: 7

Related Questions