PHP Prepared Statements function

I want to create a "general" function to deal with all my prepared statements in PHP.

I.e., I want a function like

function doStmt($sqlQuery,$types,$arg1,...,$argN) {
    (...)
    if(!$stmt = $mysqli->prepare($sqlQuery)) //error blah blah;
    if (!$stmt->bind_param($types, $arg1,...,$argN)) //error ...;
    if (!$stmt->execute()) //error ...;
    $stmt->close();
    return true;
}

My problem has to do mainly with how to dynamically set the N arguments to the doStmt function and then how to pass them to bind_param.

The reason why I want such function is so that I don't need to check for errors & close everytime I use a prepared statement.

Upvotes: 1

Views: 99

Answers (1)

xiGUAwanOU
xiGUAwanOU

Reputation: 334

Try this one:

function doStmt() {
  // You could use func_num_args() get how many arguments do you have...
  $argList = func_get_args();
  $sqlQuery = array_shift($argList);
  $types = array_shift($argList);

  // echo $sqlQuery;
  // echo $types;
  // print_r($argList);

  $stmt = $mysqli->prepare($sqlQuery);
  call_user_func_array(array($stmt, 'bind_param'), $argList);
}

doStmt('select ... ? ... ? ... ? ...', 'sss', 'string1', 'string2', 'string3');

Upvotes: 1

Related Questions