Skip to content

Instantly share code, notes, and snippets.

@ekarulf
Created February 7, 2011 10:27
Show Gist options
  • Save ekarulf/814221 to your computer and use it in GitHub Desktop.
Save ekarulf/814221 to your computer and use it in GitHub Desktop.
MySQLi Prepared Statement Helper
<?php
//
// mysqli-prepared.php
// Use PreparedQuery to ease use of prepared query calls
// Example:
// PreparedQuery($conn, "SELECT id, username FROM users WHERE email = ?", array("s", $_POST["email"])
//
function PreparedQuery($connection, $query, $params=array())
{
// Create a prepared statement
$stmt = $connection->prepare($query);
if (!$stmt)
throw new Exception("Query is not valid : '$query'");
// Bind parameters
if (count($params) > 1)
call_user_func_array(array($stmt, 'bind_param'), RefValues($params));
// Execute and buffer results into memory
$stmt->execute();
// Return results based on query type
$type = GetQueryType($query);
$result = FALSE;
if ($stmt->errno !== 0)
{
$result = FALSE;
}
else if ($type == "SELECT")
{
$meta = $stmt->result_metadata();
// Fetch field names
while ($field = $meta->fetch_field())
$parameters[] = &$row[$field->name];
call_user_func_array(array($stmt, 'bind_result'), RefValues($parameters));
$results = array();
while ($stmt->fetch())
{
$tmp = array();
foreach ($row as $key => $val)
$tmp[$key] = $val;
$results[] = $tmp;
}
$result = $results;
}
else if (in_array($type, array("INSERT", "UPDATE", "DELETE")))
{
$result = $stmt->affected_rows;
}
else // CREATE TABLE, REPLACE
{
$result = TRUE;
}
// Close the prepared statement with MySQL
$stmt->close();
return $results;
}
function GetQueryType($query)
{
$query = strtoupper($query);
$best_type = NULL;
foreach(array("SELECT", "INSERT", "UPDATE",
"DELETE", "REPLACE", "CREATE TABLE") as $type) {
$pos = strpos($query, $type);
if ($pos !== FALSE && $pos >= 0)
{
$best_type = $type;
$query = substr($query, 0, $pos);
// stop iteration early
if (strlen($query) == 0)
break;
}
}
return $best_type;
}
function RefValues($arr)
{
if (strnatcmp(phpversion(), '5.3') >= 0) //Reference is required for PHP 5.3+
{
$refs = array();
foreach($arr as $key => $value)
$refs[$key] = &$arr[$key];
return $refs;
}
return $arr;
}
@JamesCullum
Copy link

  • Doesn't work with INSERT ... ON DUPLICATE UPDATE (fix by breaking after the first match, stripping L79)
  • L63 needs to be return $result;, The S too much makes it always empty.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment