Basic PDO query

0

I'm starting with PDO and I have a problem I'm following a course which I'm copying everything at the bottom of the letter but it does not return data when doing a print_r I returned a 1, and in the database I have 3 users already entered with nombre , email y ID

and the truth is that I do not know what the problem could be, I've seen it again and again, I've tried other ways but the result leads me to it.

Thank you in advance

$conexion = new PDO('mysql:host=localhost;dbname = prueba', 'root', '');
$result = $conexion ->query('SELECT * FROM usuarios');

foreach ($result as $res)
{
    echo $res["nombre"]."<br>";
}
    
asked by felipe rodriguez 11.07.2018 в 07:55
source

3 answers

1

Try running this:

<?php
$usuario = 'root';
$contraseña = '';
try {
    $conexion = new PDO('mysql:host=localhost;dbname=prueba', $usuario, $contraseña);
} catch (PDOException $e) {
    print "¡Error!: " . $e->getMessage() . "<br/>";
    die();
}
$sentencia = $conexion->prepare('SELECT * FROM usuarios');
$sentencia->execute();

//Esta salida se acerca más al resultado que buscas
while ($result = $sentencia->fetch(PDO::FETCH_ASSOC)) {
        echo $result['nombre']."</br>";
    }
?>

It is a script of a question that I answered some time ago, I adapted it a bit for your case, I guess it would be more or less what you are looking for. If you want to see the total answer this here .

PS: Personally I think that if you are going to use PDO, it is highly recommended that you exploit the FETCH functions.

    
answered by 11.07.2018 в 09:48
1

Thank you very much everyone for answering, I already found out what my problem was and it is that in the database I was making a space I was leaving it like this

mysql: host = localhost; dbname = test

and it is without spaces, it has to be like this

mysql: host = localhost; dbname = test

thanks for the quick answers

    
answered by 11.07.2018 в 22:51
1

I told you that your code should look like this:

$conexion = new PDO('mysql:host=localhost;dbname=prueba','root','');
$result = 'SELECT * FROM usuarios';
$ejecutaResult = $conexion->prepare($result);
$ejecutaResult->execute();

        foreach ($ejecutaResult as $res) {
            echo $res["nombre"].PHP_EOL;
        }

Where as notes the changes are:

  
  • The query is left in a single variable
  •   
  • declare a new variable that will be equal to the connection object and with that same access to the prepare () method and step as   argument the variable that contains my SELECT
  •   
  • The previous variable is the same one that will access the execute method, to execute the query
  •   
  • Also if you are not passing dynamic values to your query ie variables that modify the result, try using quotes   simple instead of double
  •   

    The last variable used is the one that I will try in the foreach and I will place a new alias to go through the columns that is bringing me

        
    answered by 11.07.2018 в 08:17