Does not return data from PDO database table

Asked

Viewed 49 times

-1

It is not returning the array with the table data, at first I thought the table was empty, but it is NOT! , someone can help me?

  • The syntax of your dsn is wrong, is "mysql:host=localhost;dbname=dbphp7", and not in this way that you did

  • @jonas2591 It will probably return only the first record found in the table according to the criteria passed in the query, what is happening??

  • 1

    @jonas2591 a suggestion to be able to answer you faster about some doubt and put the code in the question, in this you put the code print.

  • I know this code, it’s from a video lesson of the Hcode Full PHP Course, if you go back to video lesson and pay attention to the code you’ll see where you’re going wrong.

2 answers

1

Code suggestion:

<?php

    $dsn = 'mysql:host=localhost;dbname=dbphp7';
    $user = 'root';
    $password = '';

    try{
        $conn = new PDO($dsn, $user, $password);
    }
    catch(PDOException $ex){
        echo 'Connection failed: ' . $e->getMessage();
    }

using the Fetchall

$stmt = $conn->prepare("SELECT * FROM tb_usuarios ORDER BY deslogin");
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

using the Fetch

$stmt = $conn->prepare("SELECT * FROM tb_usuarios ORDER BY deslogin");
$stmt->execute();

while ($linha = $stmt->fetch(PDO::FETCH_ASSOC)) {
    var_dump($linha);
}

Notice the difference between them.

Fetchall vs Fetch

0

The following is an example from the official PHP website:

<?php
    /* Execute a prepared statement by passing an array of values */
    $sql = 'SELECT name, colour, calories FROM fruit WHERE calories < :calories AND colour = :colour';
    $sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
    $sth->execute(array(':calories' => 150, ':colour' => 'red'));
    $red = $sth->fetchAll();
    $sth->execute(array(':calories' => 175, ':colour' => 'yellow'));
    $yellow = $sth->fetchAll();
?>

https://www.php.net/manual/en/pdo.prepare.php

Browser other questions tagged

You are not signed in. Login or sign up in order to post.