Searching data in database

Asked

Viewed 270 times

1

Good evening, I’m having second thoughts about a certain code. It should search all users in the database and list... however of the error...Como pode ser visto aqui

Follow the excerpt of the code where I make the instructions to retrieve 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 making this mistake here:

foto do erro

  • the error is being in php, line 80 as print shows, an unexpected character '<' check this line or post full php

  • the line 80: echo "<tr><td>" . $write['name'] . "</td><td>" . $write['email'] . "</td><td>" . $write['user'] . "</td><td>" . $write['nivel_acesso_id'] . "</td><tr>";

  • the last tag, you are not closing the <tr>, has to stay </tr> although this seems to be an html error, not php error. You can edit the question to put the full code.

  • I edited with the full code, I closed the tag, however it is not the error

  • Peter you are using mysqli and not mysql Connection. The code I demonstrated it’s not by mysqli.

  • @mistakes But when using mysql , gives Warning warning that is no longer used

Show 1 more comment

3 answers

4

Question 1, the CRASE:

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

It is usually used when you want to reference a special table or database, e.g.:

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

So normally this model is used when we want to access or manipulate "names" of databases, tables... This is not done and is not recommended either.
A good old "_" solves everything, ex:

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

No reason to use special "characters".


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

Do not use these "special quotes".
like "" . $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 conventional quotes as " código " (double quotes in this case can be used a html treatment, however, you will have to give a backslash \") and '<img src="imagem.jpg"' (quotation mark), usually use '' to echo some html code, since the HTML parameters are normally given from "parameter"(double quotes)


3rd Let’s go to the code and no 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.

            ?>

CREATION OF THE COMIC BOOK FOR TESTING:

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

Code "corrected":
I took a nap to work on that. Cara ta missing separate the query and are many different techniques. Turns on this. Remembering that the connection has to be treated the way I treated it here, no matter 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 to have lightened there and also helped hehehe, was textão. I really do not know why use mysqli along with mysql, so I treated everything directly with mysql. (Search by **PDO, mysql is no longer "used")**.

With everything set up the end is: código funcionando.

  • So, I did what you said, now giving two other different errors, check it out: Warning: mysqli_connect() expects Parameter 1 to be string, Object Given in C: wamp64 www painel_prefeitura lista_user.php on line 78 And the other error: Warning: mysqli_fetch_array() expects Parameter 1 to be mysqli_result, null Given in C: wamp64 www painel_prefeitura lista_user.php on line 79

  • My mistake, yesterday morning I didn’t have time to "read" and look for problems in the code. Finally friend, I updated, now look and tell me if you understood and if it helped you. Hugs and good developments brother! And sorry for the "sloth" yesterday, really was very busy.

  • I copied it identical to yours. And it doesn’t work. Awesome! I’m almost giving up

2

I believe the error is in this section, check:

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

Also, change your mind and for " 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>
  • the error persists

  • Check now

  • Just a hint Pedro : when you do this : SELECT * FROM user you make the selection on all fields of the table the ideal for performance is this : "SELECT name,email,user,nivel_acesso_id FROM user. Table name and fields are not used in quotes only when it is a text (string). in your query the table name looks like this usuario remove these quotes. Hugs....

  • Your is giving the following error: Warning: mysqli_connect() expects Parameter 1 to be string, Object Given in C: wamp64 www painel_prefeitura lista_user.php on line 78 ( ! ) Warning: mysql_fetch_() expects Parameter 1 array to be Resource, null Given in C: wamp64 www painel_prefeitura lista_user.php on line 79 Call St ( ! ) Notice: Use of Undefined Constant conexao - assumed 'conexao' in C: wamp64 www painel_prefeitura lista_user.php on line 84 ( ! ) Warning: mysql_close() expects Parameter 1 to be Resource, string Given in C: wamp64 www painel_prefeitura lista_user.php on line 84

  • I paid attention to the error of PHP syntax, I did not even notice in Mysql, I believe that this problem you solve with the answer of Djalma

2

For your code to work we will make some changes. But first let’s theory.

You are using the procedural form of mysql_query and is 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 noticed that you are called the bank connection of another file. Perfect. Centralize the connection to the bank in only one place of your project and avoid rework.

include "conexao.php";

Since you didn’t post anything about how the connection is being made, I’ll put how it is done 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 bank check if there were no errors:

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

To conduct a consultation based on a query you can do so:

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

To go through the query you can do using a repeat loop, exactly 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 quotes (''), instead of crasses (``).

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

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

Any doubt just comment.

  • At the time of printing the name you used [] and at the time of printing email you used ()?

  • It was just a formatting for easy viewing when applying a var_dump. I will withdraw

  • Heheheheh, I just got into the stack and it’s nice to see there’s a lot of people who help. I rewrote everything here and I just realized that you had posted the solution now. I was more "explanatory", but the way you put it is more the explanation for the answer. Thank you and sorry brother! Very good the content.

  • Djalma Manfrin, in his code giving the following error when I implement: Warning: mysql_fetch_assoc() expects Parameter 1 to be Resource, Object Given

  • Tomorrow at work I will check the reason for the mistake

  • @Pedro Ribeiro, I changed the answer to his need. I could not perform the test of the procedural form because it generated the warning Please, do not use the mysql Extension for new Developments. For this move I chose to change the response to object-oriented form. I did the test and it worked perfectly

Show 1 more comment

Browser other questions tagged

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