Return data from a class to index

Asked

Viewed 346 times

0

I’m putting it into practice PHP Object-oriented and I’m developing a CRUD of students.

I have a class to count the number of students in the bank. And I wanted to take the return of the function that counts the students and send this result to index, but I’m having a hard time doing this.

class Showstudent.php:

<?php

class MostraAluno
{
    protected $nome, $media;
    public $dns = 'mysql:host=localhost;dbname=alunos';
    public $user = 'root';
    public $pass = 'vertrigo';
    public $pdo;

    public function __construct()
    {
        try {
            $this->pdo = new PDO($this->dns, $this->user, $this->pass);
        } catch (PDOException $e) {
            die('Erro de conexao com o banco de dados: ' . $e->getMessage());
        }
    }

    public function contaAluno()
    {
        $count = "SELECT COUNT(*) AS total FROM usuarios ORDER BY nome ASC";

        $stmt_count = $this->pdo->prepare($count);
        $stmt_count->execute();
        $total = $stmt_count->fetchColumn();

        return $total;
    }
}

And the index.php:

<?php

require_once 'core/MostraAluno.php';

$mostraAluno = new MostraAluno();

$alunos = $mostraAluno->mostraAluno();
$totAlunos = $mostraAluno->contaAluno();

?>
<!DOCTYPE html>
<html>
<head>

<link rel="stylesheet" type="text/css" href="static/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="static/css/style.css">

<meta charset="utf-8">
<title>Notas - Alunos</title>
</head>
<body>

<!--
=======================================================================
                                NAVBAR
=======================================================================
-->
<nav class="navbar navbar-inverse">
<div id="inicio" class="container-fluid">

  <div class="navbar-header">
    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
      <span class="sr-only">Toggle navigation</span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </button>
    <a class="navbar-brand" href="#inicio"><b>Sistema de notas</b></a>
  </div>

  <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
    <ul class="nav navbar-nav">
        <li><a href="cadastrar.php"><u>Cadastrar novo aluno</u></a></li>
      </ul>
    <ul class="nav navbar-nav navbar-right">
      <li class="dropdown">
        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Perfil <span class="caret"></span></a>
        <ul class="dropdown-menu">
          <li role="separator" class="divider"></li>
          <li><a href="core/logout.php">Sair</a></li>
        </ul>
      </li>
    </ul>
  </div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>

<!--
=======================================================================
                                CORPO
=======================================================================
-->

<div class="row">
    <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12" style="background-color: ">
  <center><h4 class="bg-info"><b>Total de alunos: <?php echo $totAlunos; ?></b></h4></center>
    </div>
</div>

When executed the index appears only the text 'Total of students:' and does not show the return of the method.

In the archive MostraAluno I withdrew the method mostraAluno(), because my doubt is only with the method contaAluno().

Could someone tell me where I’m going wrong? I’m now starting to put into practice PHP OO and I am having difficulty returning the values of the methods to other files.

  • your table usuarios has data?

  • Because I tested your code and it worked

  • Yes. has two records

  • puts this code in your index and see which error shows: ini_set('display_errors',1);&#xA;ini_set('display_startup_erros',1);&#xA;error_reporting(E_ALL);

  • I found the error... the name of the table in the database was USUARIS -_-

  • ready. I’m glad it worked out

  • 12

    @Gabriel see this: https://answall.com/help/editing if people improve their question you should accept the change. Some reason you rejected?

  • Yes. Changes such as changing a sentence to italics, in my view, is irrelevant. It will not change anything with regard to understanding the topic and the question raised. And another, the changes only started to be made after @adventistaam has already manifested itself regarding my doubt, that is, he understood what was questioned in the topic! So I didn’t see any reason for correction, especially corrections of putting sentences in italics.

  • 11

    @Gabriel he changed much more than Italian, he corrected accentuation and punctuation, which is totally acceptable and useful and improves rather the reading. Saul also edited another question of yours that you rejected and it was a good edit, he removed redundant (as in the title) and unnecessary "greetings". Read more about it at https://pt.meta.stackoverflow.com/q/846/3635 ;)

Show 4 more comments

1 answer

1

Although you have already found the error. There is another way to do if you wanted to use one day:

    $stmt_count = $this->pdo->prepare($count);
    $stmt_count->execute();
    $total = $stmt_count-> rowCount(); // aqui ele conta o total 

The good thing to do this way is that you can make the selection of all students(in case) and just use the rowCount(); to count the total quantity, without the need to make two connections.

Browser other questions tagged

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