Doubt in listing items with PDO and PHP 7

Asked

Viewed 133 times

-2

Hello, I’m trying to make a listing using PHP 7 and PDO and I’m not getting it. Until then I made this code

<?php
$con = new PDO("mysql: dbname = banco; host = localhost", "root", "senha");
$sql = $con->prepare("SELECT * FROM turmas WHERE status='Ativo' ORDER BY id ASC LIMIT 12");
$sql->execute();
$row = $sql->fetchAll(PDO::FETCH_ASSOC);
if (count($row) === 0 ) {
    echo "<option disabled>Nenhuma Turma Cadastrada</option>";
    } else {
        while ($row){
    ?>
    <option value="<? echo $row['turma']?>"> MED <? echo $row['turma']?> </option>
    <?php
}}
?>

Since there are 12 records in the table classes, but when I go to the site, he says that there is no registered class.

Could someone help me

  • Shortly after $sql->execute(); put the line print_r($sql->errorInfo()); and give us the result.

  • Have tried running the query "SELECT * FROM classes WHERE status='Active' ORDER BY id ASC LIMIT 12" directly in the database to confirm if it is returning results?

  • The method prepare PDO should be used to prepare a query to receive the parameters with bindParam, not your case, can use the method query in place of which it shall operate.

1 answer

-1

I managed to solve with this code

<?php
$con = new PDO("mysql:dbname=banco;host=localhost", "root", "senha");
$sql = $con->prepare("SELECT * FROM turmas WHERE status = 'Ativo' ORDER BY id ASC LIMIT 12");
$sql->execute();

$row = $sql->fetchAll(PDO::FETCH_ASSOC);

if (count($row) === 0 ) {
    echo "<option disabled>Nenhuma Turma Cadastrada</option>";
}
else {
    foreach($row as $data) {
        ?>
        <option value="<?=$data['turma']?>"> MED <?=$data['turma']?> </option>
        <?php
    }
}
?>

Browser other questions tagged

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