note 121064 added to mysqli.prepare

From: Date: Wed, 10 May 2017 08:57:50 +0000
Subject: note 121064 added to mysqli.prepare
Groups: php.notes 
Request: Send a blank email to php-notes+get-209060@lists.php.net to get a copy of this message
I wasn't able to fully test the following since the server I am currently working on is missing the PHP module that allows me to call get_result on mysqli_stmt but maybe this could be helpful for someone: <?php /** * Custom {@link \mysqli} class with additional functions. */ class CustomMysqli extends \mysqli { /** * Creates a prepared query, binds the given parameters and returns the result of the executed * {@link \mysqli_stmt}. * @param string $query * @param array $args * @return bool|\mysqli_result */ public function queryPrepared($query, array $args) { $stmt = $this->prepare($query); $params = []; $types = array_reduce($args, function ($string, &$arg) use (&$params) { $params[] = &$arg; if (is_float($arg)) $string .= 'd'; elseif (is_integer($arg)) $string .= 'i'; elseif (is_string($arg)) $string .= 's'; else $string .= 'b'; return $string; }, ''); array_unshift($params, $types); call_user_func_array([$stmt, 'bind_param'], $params); $result = $stmt->execute() ? $stmt->get_result() : false; $stmt->close(); return $result; } } $db = new CustomMysqli('host', 'user', 'password', 'database', 3306); $result = $db->queryPrepared( 'SELECT * FROM table WHERE something = ? AND someotherthing = ? AND elsewhat = ?', [ 'dunno', 1, 'dontcare' ] ); if (isset($result) && $result instanceof \mysqli_result) { while (null !== ($row = $result->fetch_assoc())) { echo '<pre>'.var_debug($row, true).'</pre>'; } } ?> NOTE: If you want to use this with a PHP version below 5.4 you have to use the old ugly array() syntax for arrays instead of the short [] syntax. ---- Server IP: 72.52.91.14 Probable Submitter: 134.109.250.108 ---- Manual Page -- http://php.net/manual/en/mysqli.prepare.php Edit -- https://master.php.net/note/edit/121064 Del: integrated -- https://master.php.net/note/delete/121064/integrated Del: useless -- https://master.php.net/note/delete/121064/useless Del: bad code -- https://master.php.net/note/delete/121064/bad+code Del: spam -- https://master.php.net/note/delete/121064/spam Del: non-english -- https://master.php.net/note/delete/121064/non-english Del: in docs -- https://master.php.net/note/delete/121064/in+docs Del: other reasons-- https://master.php.net/note/delete/121064 Reject -- https://master.php.net/note/reject/121064 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#209060) next »