Help with MySQL connection

-2

I am creating a CRUD system for practices, and my code is giving error in my prepare() .

Index.php

<?php

require_once 'core/init.php';

// Abre a conexao com o banco de dados
$pdo = db_connect();

// SQL para contar o total de registros.
$sql_count = "SELECT COUNT(*) AS nome FROM usuarios ORDER BY name ASC";

// SQL para selecionar os registros
$sql = "SELECT id, nome, email, nasc FROM usuarios ORDER BY nome ASC";

// Conta o total de registros
$stmt_count = $pdo->prepare($sql_count);
$stmt_count->execute();
$total = $stmt_count->fetchColumn();

// Seleciona os registros
$stmt = $pdo->prepare($sql);
$stmt->execute();

?>

<html>
<head>

<script src="http://code.jquery.com/jquery-1.12.4.min.js"integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="crossorigin="anonymous"></script>

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>


</head>
<body>

<!-- ==================== NAVBAR INICIO - BOOTSTRAP ==================== -->
<nav class="navbar navbar-inverse">

                         Toggle navigation                                          Hoo     

<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
  <ul class="nav navbar-nav">
    <li><a href="cadastro.php"> <u>Cadastrar novo usuario</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="">Sair</a></li>
      </ul>
    </li>
  </ul>
</div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav>
<!-- ==================== NAVBAR FIM - BOOTSTRAP ==================== -->


<!-- ==================== TABLE INICIO - BOOTSTRAP ==================== -->
<p>Total de usuarios: <?php echo $total; ?></p>
<?php if($total > 0): ?>
<table class="table table-hover">
<thead>
    <th>ID</th>
    <th>Nome</th>
    <th>E-MAIL</th>
    <th>Idade</th>
    <th>Ações</th>
</thead>

<tbody>
    <?php while ($user = $stmt->fetch(PDO::FETCH_ASSOC)): ?>
        <tr>
            <td><?php echo $user['nome'] ?></td>
            <td><?php echo $user['email'] ?></td>
            <td><?php echo calcIdade($user['nasc']) ?> anos</td>
            <td>
                <a href="editar.php?id=<?php echo $user['id'] ?>" class="btn btn-primary btn-sm">Editar</a>
                <a href="deletar.php?id=<?php $user['id'] ?>" onclick="return confirm('Tem certeza que deseja excluir este usuario?'); class="btn btn-danger btn-sm">Excluir</a>
            </td>
        </tr>
    <?php endwhile; ?>
</tbody>
</table>

<?php endif; ?>
<!-- ==================== TABLE FIM - BOOTSTRAP ==================== -->

</body>
</html>

Follow the bank configuration code, init.php:

<?php

// Constantes com as credenciais para conexão com o banco de dados MySQL
define('MYSQL_HOST', 'localhost');
define('MYSQL_USER', 'root');
define('MYSQL_PASS', '');
define('MYSQL_DB_NAME', 'alpha');

// Função que chama a classe PDO
function db_connect(){
    $pdo = new PDO('mysql:host=' . MYSQL_HOST . ';dbname=' . MYSQL_DB_NAME, MYSQL_USER, MYSQL_PASS);
}

// Tentativa de conexão com o banco com tratativa de erro
try {
    $pdo = new PDO('mysql:host=' . MYSQL_HOST . ';dbname=' . MYSQL_DB_NAME, MYSQL_USER, MYSQL_PASS);
} catch (PDOException $e) {
    echo 'Erro ao conectar com a base de dados: '.$e->getMessage();
}

When I run the code it has the following error:

  

Fatal error: Call to a member function prepare () on null in C: \ wamp64 \ www \ ProjectALPHA \ index1.php on line 18

    
asked by anonymous 27.12.2016 / 22:53

1 answer

0

Thank you very much for the attention @Miguel

Problem solved. The HTML was wrong. Now it looks like this:

<?php
require_once 'core/init.php';

// abre a conexão
$pdo = db_connect();

// SQL para contar o total de registros
// A biblioteca pdo possui o método rowCount(), mas ele pode ser impreciso.
// É recomendável usar a função COUNT da SQL
// Veja o Exemplo 2 deste link: http://php.net/manual/pt_BR/pdostatement.rowcount.php
$sql_count = "SELECT COUNT(*) AS total FROM usuarios ORDER BY nome ASC";

// SQL para selecionar os registros
$sql = "SELECT id, nome, email, nasc FROM usuarios ORDER BY nome ASC";

// conta o toal de registros
$stmt_count = $pdo->prepare($sql_count);
$stmt_count->execute();
$total = $stmt_count->fetchColumn();

// seleciona os registros
$stmt = $pdo->prepare($sql);
$stmt->execute();

? >

Welcome

<!-- Latest compiled and minified CSS -->

                                 Toggle navigation                                          Hoo     

<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
  <ul class="nav navbar-nav">
    <li><a href="cadastro.php"> <u>Cadastrar novo usuario</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="">Sair</a></li>
      </ul>
    </li>
  </ul>
</div><!-- /.navbar-collapse -->

Total users:

    <?php if ($total > 0): ?>

    <table class="table table-striped">
        <thead>
            <tr>
                <th>Nome</th>
                <th>Email</th>
                <th>Idade</th>
                <th>Ações</th>
            </tr>
        </thead>

        <tbody>
            <?php while ($user = $stmt->fetch(pdo::FETCH_ASSOC)): ?>
            <tr>
                <td><?php echo $user['nome'] ?></td>
                <td><?php echo $user['email'] ?></td>
                <td><?php echo calcIdade($user['nasc']) ?> anos</td>
                <td>
                    <a href="editar.php?id=<?php echo $user['id'] ?>" class="btn btn-primary btn-sm">Editar</a>
                    <a href="core/deletar.php?id=<?php echo $user['id'] ?>" onclick="return confirm('Tem certeza de que deseja remover?');" class="btn btn-danger btn-sm">Remover</a>
                </td>
            </tr>
            <?php endwhile; ?>
        </tbody>
    </table>

    <?php else: ?>

    <?php endif; ?>

    

    
27.12.2016 / 23:49