note 89098 deleted from mysqli-stmt.bind-result by danbrown

From: Date: Sat, 21 Feb 2009 18:49:03 +0000
Subject: note 89098 deleted from mysqli-stmt.bind-result by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-150926@lists.php.net to get a copy of this message
Note Submitter: maheez at heesi dot com ---- /////////////////////////////// Im sure many of you may use this, i spent about 3hours writing this, so maybe i can save somone else some time. the mysqli bind param function only takes one variable at a time, so its difficult to pass in a few variables to fill in the placeholder space. this allows mysqli prepared statements with variable arguments, one sql template with multiple placeholders to be prepared and excuted. returns array of arrays, where the key names are the column names mysqli_stmt_bind_result hope this helps somone, Mahees. /////////////////////////////// $uname = 'mahees'; $pass = 'mahees'; $userPassArr = DataAccess::fetch('SELECT * FROM users WHERE username = ? AND password = ?', $uname, $pass); print_r($userPassArr); /* Array ( [0] => Array ( [id] => 1 [username] => mahees [password] => mahees ) ) */ $userPassArr = DataAccess::fetch('SELECT * FROM users'); print_r($userPassArr); /* Array ( [0] => Array ( [id] => 1 [username] => mahees [password] => mahees ) [1] => Array ( [id] => 4 [username] => foo [password] => bar ) [2] => Array ( [id] => 5 [username] => bar [password] => baz ) ) */ //********* function in DataAccess class ********* //im sure this can be witten better with more checks...but principle stands static function fetch() { $args = func_get_args(); $sql = array_shift($args); $link = self::establish_db_conn(); if (!$stmt = mysqli_prepare($link, $sql)) { self::close_db_conn(); die('Please check your sql statement : unable to prepare'); } $types = str_repeat('s', count($args)); array_unshift($args, $types); array_unshift($args, $stmt); call_user_func_array('mysqli_stmt_bind_param', $args); mysqli_stmt_execute($stmt); $result = mysqli_stmt_result_metadata($stmt); $fields = array(); while ($field = mysqli_fetch_field($result)) { $name = $field->name; $fields[$name] = &$$name; } array_unshift($fields, $stmt); call_user_func_array('mysqli_stmt_bind_result', $fields); array_shift($fields); $results = array(); while (mysqli_stmt_fetch($stmt)) { $temp = array(); foreach($fields as $key => $val) { $temp[$key] = $val; } array_push($results, $temp); } mysqli_free_result($result); mysqli_stmt_close($stmt); self::close_db_conn(); return $results; }

« previous php.notes (#150926) next »