2014年4月23日 星期三

[MYSQLI] bind_result() & get_result() 用法

一、 bind_result()

$id = 7;
// Use bind_result() with fetch()
$query1 = 'SELECT id,  username FROM members WHERE id = ?';
if($stmt = $mysqli->prepare($query1)){
/*
Binds variables to prepared statement
i corresponding variable has type integer
d corresponding variable has type double
s corresponding variable has type string
b    corresponding variable is a blob and will be sent in packets
*/
$stmt->bind_param('i',$id);
/* execute query /*
$stmt->execute();
/* Store the result (to get properties) */
$stmt->store_result();
/* Get the number of rows */
$num_of_rows = $stmt->num_rows;
/* Bind the result to variables */
$stmt->bind_result($id, $first_name, $last_name, $username);
while ($stmt->fetch()) {
  echo 'ID: '.$id.'<br>';
  echo 'Username: '.$username.';
}
  /* free results */
  $stmt->free_result();
  /* close statement */
二、get_result()
$id = 7;
// Use get_result() with fetch_assoc()
$query2 = 'SELECT  id,  username  FROM members WHERE id = ?';
if($stmt = $mysqli->prepare($query2 )){
/*
Binds variables to prepared statement
i corresponding variable has type integer
d corresponding variable has type double
s corresponding variable has type string
b corresponding variable is a blob and will be sent in packets
*/

$stmt->bind_param('i',$id);

/* execute query */
$stmt->execute();

/* Store the result (to get properties) */
$stmt->store_result();

/* Get the number of rows */
$num_of_rows = $stmt->num_rows;

/* Get the result */

$result = $stmt->get_result();

while ($row = $result->fetch_assoc()) {
   echo 'ID: '.$row['id'].'<br>';
   echo 'Username: '.$row['username'].'<br><br>';
}

/* free results */
$stmt->free_result();

/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();

資料來源:
http://stackoverflow.com/questions/18753262/example-of-how-to-use-bind-result-vs-get-result

沒有留言:

張貼留言