Two selects in a while with PDO

0

Hello, I'm migrating from MySQL to PDO and I'm having a hard time putting two selects in a table.

try{
        $CON = new PDO("mysql:host=localhost;dbname=tcc", 'root', '1234');
    }
    catch (PDOException $e)
    {
        echo "Erro : ".$e->getMessage();
    }

    $select = "select * from MATERIA";
    $resultado = $CON->query($select);

    $select2 = "select * from ALUNO";
    $resultado2 = $CON->query($select2);



    while($row = $resultado->fetch(PDO::FETCH_BOTH) and  $row2=$resultado2->fetch(PDO::FETCH_BOTH)){
        echo "<tr><td>".$row['NOME']."</td><td>".$row2['NOME']."</td>";
    }

The problem is that when the results of query 1 are finished, it stops listing other students, and I would like it to continue to write them.

    
asked by anonymous 05.06.2017 / 02:39

1 answer

0

As you said in the comments, your code makes little sense. It would be better if you spoke what you want, maybe some print of the project.

Anyway, with a few modifications this will help you.

<?php

try {
    $conn = new pdo('mysql:host=localhost;dbname=tcc', 'root', '1234', [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]);
} catch (PDOException $e) {
    echo "Erro: {$e->getMessage()}";
    die;
}

$stmtMaterias = $conn->prepare('SELECT * FROM 'MATERIA'');
$stmtAlunos = $conn->prepare('SELECT * FROM 'ALUNO'');

try {
    $stmtMaterias->execute();
    $stmtAlunos->execute();
} catch (PDOException $e) {
    echo "Erro: {$e->getMessage()}";
    die;
}

$materias = $stmtMaterias->rowCount() ? $stmtMaterias->fetchAll() : [];
$alunos = $stmtAlunos->rowCount() ? $stmtAlunos->fetchAll() : [];

if (count($alunos) >= count($materias)) {
    foreach ($alunos as $key => $value) {
        echo '<tr>';

        if (isset($materias[$key]['NOME'])) {
            echo "<td>{$materias[$key]['NOME']}</td>";
        }

        if (isset($value['NOME'])) {
            echo "<td>{$value['NOME']}</td>";
        }
    }
} else {
    foreach ($materias as $key => $value) {
        echo '<tr>';

        if (isset($value['NOME'])) {
            echo "<td>{$value['NOME']}</td>";
        }

        if (isset($alunos[$key]['NOME'])) {
            echo "<td>{$alunos[$key]['NOME']}</td>";
        }
    }
}
    
05.06.2017 / 03:14