Created
April 30, 2013 18:20
-
-
Save SleeplessByte/5490755 to your computer and use it in GitHub Desktop.
Executes a prepared query. Provide with a query. Use ? in the query for bind locations. Types is a string where its length equals the values array size. Returns the results in an associative array, insert id, NULL or success boolean.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Executes a prepared query | |
* | |
* @param string $query the query to execute | |
* @param string $types the types of the bind (s: string or d: integer for each value) | |
* @param mixed[] $values array of values | |
* @param string $error referenced error variable | |
* @returns null|boolean|integer|mixed[] the results | |
*/ | |
public static function do_prepared_query( $query, $types, $values, &$error ) { | |
##$counter++; | |
$mysqli = ##get_connection(); | |
if ( empty( $mysqli ) ) | |
return NULL; | |
$stmt = $mysqli->prepare( $query ); | |
if( !empty( $types ) && !empty( $values ) ) | |
{ | |
if ( is_array( $types ) ) | |
$types = implode( '', $types ); | |
$bind_names[] = $types; | |
for ( $i = 0; $i < count( $values ); $i++ ) | |
{ | |
// Create a variable bind$i which holds the value at $i | |
$bind_name = 'bind' . $i; | |
$$bind_name = $values[$i]; | |
$bind_names[] = &$$bind_name; | |
} | |
$return = call_user_func_array( array( $stmt, 'bind_param' ), $bind_names ); | |
} | |
// Execute query | |
$execution = $stmt->execute(); | |
if ( !$execution ) { | |
$error = $stmt->error; | |
$stmt->close(); | |
if ( strpos( $query, 'INSERT' ) !== false ) | |
return 0; | |
return NULL; | |
} | |
// Create one dimenial array | |
$meta = $stmt->result_metadata(); | |
if ( $meta != false ) { | |
$results = array(); | |
while ( $field = $meta->fetch_field() ) { | |
$var = $field->name; | |
$$var = NULL; | |
$results[ $field->name ] = &$$var; | |
} | |
call_user_func_array(array($stmt, 'bind_result'), $results); | |
$rows = array(); | |
while( $stmt->fetch() ) | |
array_push( $rows, unserialize( serialize( $results ) ) ); | |
} | |
$stmt->close(); | |
if ( $meta ) | |
return $rows; | |
if ( strpos( $query, 'INSERT' ) !== false ) | |
return $mysqli->insert_id; | |
return $execution; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment