O fator decisivo para mim é se chamo minhas colunas de consulta usando
*
. Usando bind_result()
seria melhor para isso:
// Use bind_result() with fetch()
$query1 = 'SELECT id, first_name, last_name, username FROM table WHERE id = ?';
Usando get_result()
seria melhor para isso:
// Use get_result() with fetch_assoc()
$query2 = 'SELECT * FROM table WHERE id = ?';
Exemplo 1 para $query1
usando bind_result()
$query1 = 'SELECT id, first_name, last_name, username FROM table WHERE id = ?';
$id = 5;
if($stmt = $mysqli->prepare($query)){
/*
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 '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();
Exemplo 2 para $query2
usando get_result()
$query2 = 'SELECT * FROM table WHERE id = ?';
$id = 5;
if($stmt = $mysqli->prepare($query)){
/*
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();
/* Get the result */
$result = $stmt->get_result();
/* Get the 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();
Como você pode ver, você não pode usar
bind_result
com *
. No entanto, get_result
funciona para ambos, mas bind_result
é mais simples e tira um pouco da bagunça com $row['name']
. bind_result()
Prós:
- Mais simples
- Não há necessidade de mexer com
$row['name']
- Usa
fetch()
Contras:
- Não funciona com consultas SQL que usam
*
get_result()
Prós:
- Funciona com todas as instruções SQL
- Usa
fetch_assoc()
Contras:
- Deve mexer com variáveis de array
$row[]
- Não tão elegante
- requer driver nativo MySQL (mysqlnd )