php - Example of how to use bind_result vs get_result -
i see example of how call using bind_result vs. get_result , purpose of using 1 on other.
also pro , cons of using each.
what limitation of using either , there difference.
the deciding factor me, whether call query columns using *
.
using bind_result()
better this:
// use bind_result() fetch() $query1 = 'select id, first_name, last_name, username table id = ?';
using get_result()
better this:
// use get_result() fetch_assoc() $query2 = 'select * table id = ?';
example 1 $query1
using bind_result()
$query1 = 'select id, first_name, last_name, username table id = ?'; $id = 5; if($stmt = $mysqli->prepare($query)){ /* binds variables prepared statement corresponding variable has type integer d corresponding variable has type double s corresponding variable has type string b corresponding variable blob , sent in packets */ $stmt->bind_param('i',$id); /* execute query */ $stmt->execute(); /* store result (to properties) */ $stmt->store_result(); /* number of rows */ $num_of_rows = $stmt->num_rows; /* bind result variables */ $stmt->bind_result($id, $first_name, $last_name, $username); while ($stmt->fetch()) { echo 'id: '.$id.'<br>'; echo 'first name: '.$first_name.'<br>'; echo 'last name: '.$last_name.'<br>'; echo 'username: '.$username.'<br><br>'; } /* free results */ $stmt->free_result(); /* close statement */ $stmt->close(); } /* close connection */ $mysqli->close();
example 2 $query2
using get_result()
$query2 = 'select * table id = ?'; $id = 5; if($stmt = $mysqli->prepare($query)){ /* binds variables prepared statement corresponding variable has type integer d corresponding variable has type double s corresponding variable has type string b corresponding variable blob , sent in packets */ $stmt->bind_param('i',$id); /* execute query */ $stmt->execute(); /* result */ $result = $stmt->get_result(); /* number of rows */ $num_of_rows = $result->num_rows; while ($row = $result->fetch_assoc()) { echo 'id: '.$row['id'].'<br>'; echo 'first name: '.$row['first_name'].'<br>'; echo 'last name: '.$row['last_name'].'<br>'; echo 'username: '.$row['username'].'<br><br>'; } /* free results */ $stmt->free_result(); /* close statement */ $stmt->close(); } /* close connection */ $mysqli->close();
as can see can't use bind_result
*
. however, get_result
works both, bind_result
simpler , takes out of mess $row['name']
.
bind_result()
pros:
- simpler
- no need mess
$row['name']
- uses
fetch()
cons:
- doesn't work sql query use
*
get_result()
pros:
- works sql statements
- uses
fetch_assoc()
cons:
- must mess around array variables
$row[]
- not neat
- requires mysql native driver (mysqlnd)
Comments
Post a Comment