Searching for data in the database

1

Good evening, I'm doubtful in a certain code. It should fetch all users from the database and list ... but the error ...

Here is the snippet of the code where I make the instructions to fetch the data:

<?php
session_start();
include "seguranca.php";
include "conexao.php";
?>

<!DOCTYPE html>
<html lang="pt-br">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Painel Administrativo">
    <meta name="author" content="Prisma Design">
    <link rel="icon" href="imagens/favicon.ico">

    <title>Painel Administrativo</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/ie10-viewport-bug-workaround.css" rel="stylesheet">
    <link href="css/dashboard.css" rel="stylesheet">
    <script src="js/ie-emulation-modes-warning.js"></script>
  </head>

  <body>

    <nav class="navbar navbar-inverse navbar-fixed-top">
      <div class="container-fluid">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            <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="administrativo.php">Painel Administrativo 0.1 BETA</a>
        </div>
        <div id="navbar" class="navbar-collapse collapse">
          <ul class="nav navbar-nav navbar-right">
            <li><a href="#">Painel</a></li>
            <li><a href="#">Configurações</a></li>
            <li><a href="#">Perfil</a></li>
            <li><a href="#">Ajuda</a></li>
          </ul>
          <form class="navbar-form navbar-right">
            <input type="text" class="form-control" placeholder="Procurar...">
          </form>
        </div>
      </div>
    </nav>

    <div class="container-fluid">
      <div class="row">
        <div class="col-sm-3 col-md-2 sidebar">
          <ul class="nav nav-sidebar">
            <li><a href="administrativo.php">Vista geral</a></li>
            <li><a href="#">Suporte</a></li>
          </ul>
          <ul class="nav nav-sidebar">
            <li><a href="adiciona_user.php">Adicionar usuário</a></li>
            <li class="active"><a href="lista_user.php">Listar usuários <span class="sr-only">(current)</span></a></li>
          </ul>
          <ul class="nav nav-sidebar">
            <li><a href="logout.php">Logout</a></li>
          </ul>
        </div>
        <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
          <h3 class="page-header"><?php echo "Bem vindo:  ".$_SESSION['usuarioNome']; ?></h3>
        </div>
        <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
          <table class="table table-hover">
            <tr>
            <th>Nome</th>
            <th>E-mail</th>
            <th>Usuário</th>
            <th>Nível</th>
            </tr>
            <?
              $lista = mysqli_connect($conectar, "SELECT * FROM 'usuario'");
              while($escrever=mysql_fetch_array($lista)){
                echo “<tr><td>” . $escrever[’nome’] . “</td><td>” . $escrever[’email’] . “</td><td>” . $escrever[’usuario’] . “</td><td>” . $escrever[’nivel_acesso_id’] . “</td></tr>”;

              }
                echo “</table>”;
                </table>
                mysql_close(conexao);

            ?>
            <tr>

          </table>
        </div>
      </div>
    </div>
  </body>
</html>

EDIT!

I did what you told me, now you're giving this error here:

    
asked by anonymous 18.07.2017 / 03:05

3 answers

4

1st Question, CRASE:

<?php
    mysqli_connect($conectar, "SELECT * FROM 'usuario'");
?>

Normally it is used when wanting to reference a special table or database, eg:

mysql -> CREATE DATABASE 'cadastro de alunos';
mysql -> SELECT 'Matrícula' FROM alunos;

So usually this model is used when we want to access or manipulate "names" of banks, tables ... This is not done and is not recommended as well. Home   A good old "_" solves everything, eg:

mysql -> CREATE DATABASE cadastro_de_alunos;
mysql -> SELECT * FROM alunos;

You do not have to use special "characters."

2nd Single and Double Quotes NOTE: Until stackoverflow uses this "rule", it does not recognize String or Quotes.

  

Do not use these "special" quotes.
  as "" . $ write ['name']

 “<tr><td>” . $escrever[’nome’]
 echo “<tr><td>” . $escrever[’nome’] . “</td><td>” . $escrever[’email’] . “</td><td>” . $escrever[’usuario’] . “</td><td>” . $escrever[’nivel_acesso_id’] . “</td></tr>”;
  

Use the conventional quotes like " código " (double quotation marks, in this case   can be used an html treatment, however, you will have to give a    \" ) and '<img src="imagem.jpg"' (single quote)   is usually used to give an echo in some html code, since the   HTML parameters are typically given from   " parameter (double quotes)

     

3ª Let's go to the code and without bla bla bla hehehehe!    Your code:

 <?
              $lista = mysqli_connect($conectar, "SELECT * FROM usuario");
              while($escrever=mysql_fetch_array($lista))
              {
                // Não entendi o porque usar MYSQLI com MYSQL ???

                echo '<tr><td>' . $escrever['nome'] . '</td><td>' . $escrever['email'] . '</td><td>' . $escrever['usuario'] . '</td><td>' . $escrever['nivel_acesso_id'] . '</td></tr>';

              }
                echo '</table>';

               </table>               // Código solto.

                mysql_close(conexao); // mysql_close? Mais você não abriu a conexao com mysqli e mesmo assim, lembre-se $conexao, a chave($).
                // mysql_close é uma funçao entao.
                mysql_close($conexao); // Usando o molde que você criou, não sei de onde vem essa variável, não mostra ela sendo atribída.

            ?>

EDIT CREATION for testing:

mysql> create table cadastro (
    -> nome varchar(30) not null,
    -> email varchar(50) not null ) DEFAULT CHARSET utf8;

Corrected code:
I gave a sleeper to work this better.   There is no need to separate the query and there are many different techniques. You get into it here. Remembering that the connection has to be handled the way I've been here , regardless of how you use it.

<?php

        // Criei esse modelo para ter uma conexao qualquer.
        $conexao = @mysql_connect("localhost","root","");
        mysql_select_db("cadastro"); // Criei e conectei num BD que criei


        // Separa a query na variavel $lista
        $lista = mysql_query("SELECT * from cadastro");
        // Enquanto $escrever != null retorna para $escrever em modo de Array cada linha. 
        while($escrever=mysql_fetch_array($lista))
        {
            echo '<tr><td>' . $escrever["nome"] . '</td><td>' . $escrever["email"] . '</td></tr>'; 
        }

        // Fechando a conexao
        mysql_close($conexao); 
?>
  

I hope I have cleared up there and also helped hehehe, it was textão. I really do not know why to use mysqli along with mysql , so I treated everything straight with mysql. (Search for ** PDO , mysql is no longer "most used") **.

With everything set up the end is:

    
18.07.2017 / 06:58
2

I believe the error is in this section, check:

echo “</table>”;
</table>                 <----------------------------
mysql_close(conexao);

Also, change and by " or '

Corrected code:

<?php
session_start();
include "seguranca.php";
include "conexao.php";
?>

<!DOCTYPE html>
<html lang="pt-br">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Painel Administrativo">
    <meta name="author" content="Prisma Design">
    <link rel="icon" href="imagens/favicon.ico">

    <title>Painel Administrativo</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/ie10-viewport-bug-workaround.css" rel="stylesheet">
    <link href="css/dashboard.css" rel="stylesheet">
    <script src="js/ie-emulation-modes-warning.js"></script>
  </head>

  <body>

    <nav class="navbar navbar-inverse navbar-fixed-top">
      <div class="container-fluid">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            <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="administrativo.php">Painel Administrativo 0.1 BETA</a>
        </div>
        <div id="navbar" class="navbar-collapse collapse">
          <ul class="nav navbar-nav navbar-right">
            <li><a href="#">Painel</a></li>
            <li><a href="#">Configurações</a></li>
            <li><a href="#">Perfil</a></li>
            <li><a href="#">Ajuda</a></li>
          </ul>
          <form class="navbar-form navbar-right">
            <input type="text" class="form-control" placeholder="Procurar...">
          </form>
        </div>
      </div>
    </nav>

    <div class="container-fluid">
      <div class="row">
        <div class="col-sm-3 col-md-2 sidebar">
          <ul class="nav nav-sidebar">
            <li><a href="administrativo.php">Vista geral</a></li>
            <li><a href="#">Suporte</a></li>
          </ul>
          <ul class="nav nav-sidebar">
            <li><a href="adiciona_user.php">Adicionar usuário</a></li>
            <li class="active"><a href="lista_user.php">Listar usuários <span class="sr-only">(current)</span></a></li>
          </ul>
          <ul class="nav nav-sidebar">
            <li><a href="logout.php">Logout</a></li>
          </ul>
        </div>
        <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
          <h3 class="page-header"><?php echo "Bem vindo:  ".$_SESSION['usuarioNome']; ?></h3>
        </div>
        <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
          <table class="table table-hover">
            <tr>
            <th>Nome</th>
            <th>E-mail</th>
            <th>Usuário</th>
            <th>Nível</th>
            </tr>
            <?
              $lista = mysqli_connect($conectar, "SELECT * FROM 'usuario'");
              while($escrever=mysql_fetch_array($lista)){
                echo "<tr><td>" . $escrever[’nome’] . "</td><td>" . $escrever[’email’] . "</td><td>" .
                $escrever[’usuario’] . "</td><td>" . $escrever[’nivel_acesso_id’] . "</td></tr>";

              }
                mysql_close(conexao);

            ?>
            </table>
          </table>
        </div>
      </div>
    </div>
  </body>
</html>
    
18.07.2017 / 04:42
2

For your code to work let's make some changes. But first let's theory.

You are using the procedural form of mysql_query and you are skipping a few steps. If you want to know more, there is the object-oriented form of mysqli_query . I addressed the differences in how to use them here >.

I realized that you are called the bank connection from another file. Perfect. Centralize the connection to the bank in one place of your project and avoid rework.

include "conexao.php";

As you have not posted anything about how the connection is being made, I'll put it as it is in object-oriented form: (Not that yours is wrong)

// Conecta ao banco de dados
$con = new mysqli('localhost', 'ususario', 'senha', 'banco');

Tip: After connecting the database, check for errors:

/* valida conexão ao banco */
if (mysqli_connect_errno()) {
    printf("Falha na conexão ao banco: %s\n", mysqli_connect_error());
    exit();
}

To perform a query based on a query you can do this:

// Monta e executa uma consulta SQL
$sql = "SELECT * FROM 'usuario' LIMIT 5";
$query = mysqli_query($con, $sql);

To walk through the query you can do using a loop repetition, just as you are doing:

// Para cada resultado encontrado...
while ($usuario = mysqli_fetch_assoc($query)) {
    // Exibe um link com a notícia
    echo $usuario['nome'] . ' - ' . $usuario['email'];
    echo '<br/>';
} // fim while

Note that in the array $usuario['nome'] is single quotation marks ( '' ), instead of quotes ('').

And a hint to display the total of lines coming in the query

// Total de notícias
echo 'Total de notícias: ' . mysqli_num_rows($query);

Any questions just comment.

    
18.07.2017 / 13:17