I cannot bring the database data from more than one table

Asked

Viewed 678 times

1

I’m learning how to do an admin, and then I created some tables in the database, but I don’t know why I can only insert and delete data from the user table and project table. Must be some silly mistake, below I’ll show you how I created my codes.

Table that is right with php that brings the data

CREATE TABLE `usuarios` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`nome` VARCHAR( 50 ) NOT NULL ,
`email` VARCHAR( 50 ) NOT NULL ,
`foto` VARCHAR( 100 ) NOT NULL
) ENGINE = MYISAM ;

HTML

       <?php
        // Seleciona todos os usuários
        $sql = mysql_query("SELECT * FROM usuarios ORDER BY nome");

        // Exibe as informações de cada usuário
        while ($usuario = mysql_fetch_object($sql)) {
            // Exibimos o nome e email
            echo "<p><b>Nome:</b> " . $usuario->nome ." </p>";
            echo "<p><b>Email:</b> " . $usuario->email . "</p>";
            // Exibimos a foto
            echo "<figure><img src='fotos/".$usuario->foto."' alt='Foto de exibição' /></figure>";
            echo "<iframe width='400' height='200' src='". $usuario->video ."' frameborder='0' allowfullscreen></iframe>";
            echo "<form action='deleta.php' method='post'>
                    <input type='hidden' name='id' value='". $usuario->id ."'>
                    <input type='submit' name='deletar' value='deletar' />
                </form>";
        }


        ?>  

Table that is wrong with php that brings the data

    CREATE TABLE `tb_projetos` (
    `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    `texto` VARCHAR( 50 ) NOT NULL ,
    `foto` VARCHAR( 100 ) NOT NULL
    ) ENGINE = MYISAM ;

       <?php
        // Seleciona todos os usuários
        $sql = mysql_query("SELECT * FROM tb_projetos ORDER BY nome");

        // Exibe as informações de cada usuário
        while ($usuario = mysql_fetch_object($sql)) {
            // Exibimos a foto
            echo "<figure><img src='fotos/".$usuario->foto."' alt='Foto de exibição' /></figure>";
            echo "<textarea>".$usuario->texto."</textarea>";
            echo "<form action='deleta-fotos.php' method='post'>
                    <input type='hidden' name='id_proj' value='". $usuario->id_proj."'>
                    <input type='submit' name='deletar' value='deletar' />
                </form>";
        }


        ?>

This is the php code that connects to the database and brings the data, in the table that works the code is the same and only changes the fields

            <?php
            include "conexao.php";

            // Se o usuário clicou no botão cadastrar efetua as ações
            if ($_POST['cadastrar']) {

                // Recupera os dados dos campos
                $texto = $_POST['texto'];
                $ft_projetos = $_FILES["foto"];

                // Se a foto estiver sido selecionada
                if (!empty($foto["name"])) {

                    // Largura máxima em pixels
                    $largura = 2000;
                    // Altura máxima em pixels
                    $altura = 1080;
                    // Tamanho máximo do arquivo em bytes
                    $tamanho = 1000;

                    // Verifica se o arquivo é uma imagem
                    if(!eregi("^image\/(pjpeg|jpeg|png|gif|bmp)$", $ft_projetos["type"])){
                       $error[1] = "Isso não é uma imagem.";
                    } 

                    // Pega as dimensões da imagem
                    $dimensoes = getimagesize($ft_projetos["tmp_name"]);

                    // Verifica se a largura da imagem é maior que a largura permitida
                    if($dimensoes[0] > $largura) {
                        $error[2] = "A largura da imagem não deve ultrapassar ".$largura." pixels";
                    }

                    // Verifica se a altura da imagem é maior que a altura permitida
                    if($dimensoes[1] > $altura) {
                        $error[3] = "Altura da imagem não deve ultrapassar ".$altura." pixels";
                    }

                    // Verifica se o tamanho da imagem é maior que o tamanho permitido
                    if($arquivo["size"] > $tamanho) {
                        $error[4] = "A imagem deve ter no máximo ".$tamanho." bytes";
                    }

                    // Se não houver nenhum erro
                    if (count($error) == 0) {

                        // Pega extensão da imagem
                        preg_match("/\.(gif|bmp|png|jpg|jpeg){1}$/i", $ft_projetos["name"], $ext);

                        // Gera um nome único para a imagem
                        $nome_imagem = md5(uniqid(time())) . "." . $ext[1];

                        // Caminho de onde ficará a imagem
                        $caminho_imagem = "fotos/" . $nome_imagem;

                        // Faz o upload da imagem para seu respectivo caminho
                        move_uploaded_file($ft_projetos["tmp_name"], $caminho_imagem);

                        // Insere os dados no banco
                        $sql = mysql_query("INSERT INTO tb_projetos VALUES ('', '".$texto."', '".$nome_imagem."')");

                        // Se os dados forem inseridos com sucesso
                        if ($sql){
                            echo "Você foi cadastrado com sucesso.";
                        }
                    }

                    // Se houver mensagens de erro, exibe-as
                    if (count($error) != 0) {
                        foreach ($error as $erro) {
                            echo $erro . "<br />";
                        }
                    }
                }
            }
            ?>
  • 1

    Edit your question and add which error is occurring, either a code or a printscreen.

  • Patrick Maciel, There is no way I can do this because there are no errors displayed on the screen, I will post php that makes the whole process for you analyze

  • To facilitate debug, always run your queries like this: $res = mysq_query('SELECT .....') or die(mysql_error);

  • Which php version to use? ereg was deprecated from php5.3 it is good to exchange it for preg_match when you can.

  • i am using phpmyadmin version 4.2.11

  • rray, I put the or die(mysql_error); and there was no error on the screen, and that’s what makes me more intrigued because the user table works perfectly and the codes only change the fields and table name do not know pq does not work

  • 1

    At the beginning of the file put: ini_set('display_errors', true); error_reporting(E_ALL);. In the die() I forgot to put the kinship, the right one is the so: or die(mysql_error());

Show 3 more comments

2 answers

4

I don’t know if you understood that little detail:

$sql = mysql_query("SELECT * FROM tb_projetos ORDER BY nome");

In the second part, you are creating a Query ( Request ) to the * ( All ) table database tb_projects, ordering through the countryside name, ...ORDER BY nome");.

However, your project table ( tb_projects ) does not have the field name :

CREATE TABLE `tb_projetos` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`texto` VARCHAR( 50 ) NOT NULL ,
`foto` VARCHAR( 100 ) NOT NULL
) ENGINE = MYISAM ;

Take a look at this out of this Page:

Note: If a column is AUTO_INCREMENT (like the "id" column) or TIMESTAMP (like the "reg_date" column), it is no need to be specified in the SQL query; Mysql will Automatically add the value.

  • Yuri Calistrato, I removed the ORDER BY name from the second table and still insert nothing in the bank and no error on the screen

  • In this case, is the table not being displayed? According to the code, it makes a query in the database and displays. There is no insertion in this code. Is there nothing missing to add the question? In this view he puts the project data on the page and a small form for removal. Isn’t he removing? Or something different? It’s kind of dubious.

  • then, in tb_projects the data is not being inserted, maybe if it had been inserted would normally be displayed as in the users table that differs little from this table is what is happening

  • What’s happening according to your code is $sql = mysql_query("INSERT INTO tb_projetos VALUES ('', '".$texto."', '".$nome_imagem."')"); where you are passing an empty character at the beginning of VALUES('',..., when it is used AUTO_INCREMENT there is no need to put anything and you are passing a character.

  • ok I removed the empty space and still not entering the data in this table, the funny thing is that in the user table is with this space and everything works correctly $sql = mysql_query("INSERT INTO users VALUES (', '".$name."', '".$email."','".$video."', '".$filename."')"); This is the insertion of the user table

  • In the example of Page explains the insertion command with INSERT INTO <Nome da tabela>(campo_01,campo_02,campo_03) VALUES (valor_01,valor_02,valor_03); , make the test by explaining the columns. Maybe it will solve.

Show 1 more comment

0

Your "tb_projects" table does not have the "name" field, remove "ORDER BY name".

  • Kayo Bruno, as I had told Yuri I withdrew and continued the same thing

  • You are also trying to access $usuario->id_proj when it was actually supposed to be $usuario->id

  • I fixed it too and still not entering, this id you mentioned was for me to delete the screen record

Browser other questions tagged

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