Database query php and mysql PDO


Someone who can help me ..... I want to print the userid, as I already have in the html, it's just an echo "$ result" ....


include "conexion.php";

$user = $_SESSION['usuario'];

$idusuario="SELECT id_usuario FROM usuarios WHERE usuario = $user";



$result = $id->fetch(\PDO::FETCH_ASSOC)

The connection to the database is by PDO

asked by Ricardo Jesus Jarquin Perez 05.12.2017 в 05:47

1 answer


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>';
answered by 05.12.2017 в 09:55