Skip to main content
Tweeted twitter.com/StackCodeReview/status/1162242714538106882
edited tags
Link
200_success
  • 145.7k
  • 22
  • 191
  • 481
Source Link
potato
  • 1.1k
  • 5
  • 16

php one-time prepared statement execution function

I use prepared statements often even when I only need to execute the statement once (for security), so I implemented a function to abstract away all the function calls on the mysqli_stmt object, as well as bind_param()'s first argument since as far as my tests show it works identically even when int parameters are marked as strings.

<?php
$conn = new mysqli('localhost', 'name', 'password', 'db');

if ($conn->connect_error)
    die('Connection to database failed: ' . $conn->connect_error);

function stmt($query, $params){
   
   array_unshift($params, str_repeat('s', sizeof($params)));
   for($i = 1; $i < sizeof($params); $i++){
      $params[$i] = &$params[$i];
   }
   
   $stmt = $GLOBALS['conn']->stmt_init();
   $stmt->prepare($query);
   $method = new ReflectionMethod('mysqli_stmt', 'bind_param');
   $method->invokeArgs($stmt, $params);
   $stmt->execute();
   
   if($stmt->error){
      $result = ['error' => $stmt->error];
   } else {
      $result = $stmt->get_result();
   }
   
   $stmt->close();
   return $result;
}
?>

Usage example:

<?php
   $result = stmt('SELECT * FROM table_name WHERE id IN(?,?,?)', [1,2,3]);
?>