If everything went well, you just have to go through the results, for example with a while
:
while($result = $id->fetch( PDO::FETCH_ASSOC )){
print $result['id_usuario'].'<br>';
}
If what you want is to choose the set of results to go through later you can use fetchAll()
:
$result = $id->fetchAll( PDO::FETCH_ASSOC );
// Luego lo recorres cuando quieres
foreach( $result as $datos ) {
print $datos['id_usuario'].'<br>';
}
Keep in mind that $pdo->fetch()
returns the first row of the result set and advances the pointer. While $pdo->fetchAll()
returns the full set of results.
If you just wait for a row you should add a LIMIT 1
to the query and you can also do without while
. On the other hand, you should bin with ?
the parameters, it does not make sense to use prepared statements and concatenate the parameters directly in the query:
$idusuario="SELECT id_usuario FROM usuarios WHERE usuario = ? LIMIT 1";
$id=$conexion->prepare( $idusuario );
$id->execute( array($user) );
$result = $id->fetch( PDO::FETCH_ASSOC );
print $result['id_usuario'].'<br>';