Print column created in Select in PHP

Asked

Viewed 63 times

1

I have a table of projects and within this projects I have several students. I made a select in both tables to count how many students there are in each project, so I selected so :

Select inscricao.id, 
       inscricao.titulo, 
       inscricao.orientador, 
       inscricao.email_professor, 
       inscricao.escola, 
       inscricao.habilitacao, 
       inscricao.serie, 
       (select count(alunos.id_inscricao) as 'qtde_alunos' from alunos where alunos.id_inscricao=inscricao.id) 
from inscricao order by inscricao.titulo

But I didn’t understand how to print the column that was created to count the records in PHP.

I took the column like this:

while ($registro = mysqli_fetch_array($resultado))
{   
        id = $registro['id'];
        $titulo = utf8_decode($registro['titulo']);
        $escola = utf8_decode($registro['escola']);
        $habilitacao = utf8_decode($registro['habilitacao']);
        $serie = $registro['serie'];
        $qtde_alunos =$registro['qtde_alunos'];
 }

But it does not print the value of the variable $qtde_alunos.

1 answer

3

You need to add the alias in the sub-select result instead of inside it:

 select inscricao.id,
       inscricao.titulo,
       inscricao.orientador,
       inscricao.email_professor,
       inscricao.escola,
       inscricao.habilitacao,
       inscricao.serie,
       (select count(alunos.id_inscricao) -- não aqui
          from alunos
         where alunos.id_inscricao = inscricao.id) as 'qtde_alunos' -- aqui
  from inscricao
 order by inscricao.titulo

Use the var_dump function to view variables in more detail, this will make your life much easier:

while ($registro = mysqli_fetch_array($resultado)) {
     var_dump($resultado);
}

Browser other questions tagged

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