note 85470 modified in mysqli-stmt.bind-result by felipe
| From: | felipe@php.net | Date: | Sat, 13 Sep 2008 00:37:41 +0000 |
| Subject: | note 85470 modified in mysqli-stmt.bind-result by felipe | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-144385@lists.php.net to get a copy of this message | ||
lot of people don't like how bind_result works with prepared statements! it requires you to
pass long list of parameters which will be loaded with column value when the function being called.
To solve this, i used call_user_func_array function and result_metadata functions. which make easy
and automatically returns an array of all columns results stored in an array with column names.
please don't forget to change setting variables with your own credentials:
<?php
$host = 'localhost';
$user = 'root';
$pass = '1234';
$data = 'test';
$mysqli = new mysqli($host, $user, $pass, $data);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($stmt = $mysqli->prepare("SELECT * FROM sample WHERE t2 LIKE ?")) {
$tt2 = '%';
$stmt->bind_param("s", $tt2);
$stmt->execute();
$meta = $stmt->result_metadata();
while ($field = $meta->fetch_field())
{
$params[] = &$row[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $params);
while ($stmt->fetch()) {
foreach($row as $key => $val)
{
$c[$key] = $val;
}
$result[] = $c;
}
$stmt->close();
}
$mysqli->close();
print_r($result);
?>
--was--
lot of people don't like how bind_result works with prepared statements! it requires you to
pass long list of parameters which will be loaded with column value when the function being called.
To solve this, i used call_user_func_array function and result_metadata functions. which make easy
and automatically returns an array of all columns results stored in an array with column names.
please don't forget to change setting variables with your own credentials:
<?php
$host = 'localhost';
$user = 'root';
$pass = '1234';
$data = 'test';
$mysqli = new mysqli($host, $user, $pass, $data);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($stmt = $mysqli->prepare('SELECT * FROM user WHERE usr_name LIKE ?'))
{
$param_1 = '%';
$stmt->bind_param('s', $param_1);
$stmt->execute();
$meta = $stmt->result_metadata();
while ($field = $meta->fetch_field())
{
$arr_result[] = &$t[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $arr_result);
while($stmt->fetch())
{
print_r($t);
}
$stmt->close();
}
$mysqli->close();
?>
http://php.net/manual/en/mysqli-stmt.bind-result.php