note 68891 deleted from function.mysqli-prepare by hholzgra
| From: | hholzgra@php.net | Date: | Sat, 29 Sep 2007 12:01:10 +0000 |
| Subject: | note 68891 deleted from function.mysqli-prepare by hholzgra | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-130924@lists.php.net to get a copy of this message | ||
Note Submitter: j dot andrew dot mcentire at gmail dot com
----
Advancing on my previous note to modify the mysqli_stmt and mysqli classes; I've coded the
following to allow the passing of an array rather than a list of variables to
mysqli_stmt_bind_param. As written, it is for my DB class created specifically for inserts, but is
extensible to accomidate various uses. For the dynamic quality of my website, I wanted a function
that would allow me to fetch and insert variable numbers of values from and into a table:
<?php
class PS extends mysqli_stmt { };
class DB extends mysqli {
public function type ( $var ) {
switch ( gettype( $var ) ) {
case 'integer':
return 'i';
break;
case 'double':
return 'd';
break;
case 'string':
return 's';
break;
case 'boolean':
case 'array':
case 'object':
case 'resource':
case 'NULL':
default:
return NULL;
break;
} // could re-write to return first character, or remove breaks. Meh.
public function arr_to_arg ( $array ) {
$keys = $vals = $type = $args = NULL;
foreach ( $array as $key => $val ) {
$keys .= $key . ", ";
$vals .= "?, ";
$type .= $this->type( $vals );
$args .= '$array[\'' . $key . '\'], ';
}
$keys = rtrim( $keys, ", " );
$vals = rtrim( $vals, ", " );
$type = "'" . $type . "', ";
$args = $type . rtrim( $args, ", " );
return array( $keys, $vals, $args );
}
public function prepared_insert ( $table, $array ) {
list( $keys, $vals, $args ) = $this->arr_to_arg( $array );
$query = "INSERT INTO ${table} (${keys}) VALUES (${vals})";
$PS = new PS( $this, $query );
$line = "\$PS->bind_param( $args );";
eval ( $line );
$PS->execute( );
$PS->close( );
}
}
?>