SELECT pulling data from Database

Asked

Viewed 668 times

1

I’m not getting a select to pull the data from the database, I wish someone could help me...

<!DOCTYPE html>

<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
    <center>

        <h1>Adicionar ítem e categoria</h1>

        <form action="adicionar_item.php" method="post">
            <p><label for="item">ítem:</label>
            <input type="text" name="item" id="item" autofocus></p>


            <p><label for="categoria">Selecione a categoria:</label> <select name="categoria" id="categoria">
                <option></option>                
            <?php

            $sql="SELECT nome FROM categoria";
            $resultado=$conexao->query($sql);

            while($dados = $resultado->fetch_assoc()){
                echo "<option value=".$dados['nome'].">".$dados['nome']."</option>";
            }

            ?>
            </select></p>

            <input type="submit" value="Cadastrar">
        </form>

    </center>        
    </body>
</html>
  • what happens, makes some mistake, can explain better?

  • select does not show the categories that are already in the database, select is empty

  • your code seems correct to me, it just doesn’t show up where you initialized the connection variable $conexao

  • I managed to solve it, the problem was that I had not made the command to pull from the database. Now I’m facing new issues with adding the item in the database part

2 answers

1

You have not made the connection in the Database, if you are using PDO, you must create a new connection:

$conexao = new PDO('mysql:host=servidor;dbname=bancodedados', 'usuario', 'senha')
  • This is probably coming from the variable $conexao.

  • I had made a file that made that connection, I just hadn’t included in that file to add, that’s what was missing

0

now the problem is the following, to add the item, I need only type which will be the item and select the category to which it will be added, now I’m having difficulty to insert the item in the selected category, my code is like this

<?php
include("conecta.php");

$item=$_POST['item'];
$categoria=$_POST['categoria'];

$sql="INSERT INTO itens (item, id_cat) VALUES (\"$item\", \"$categoria\")";

$conexao->query($sql);

$linhasAfetadas=$conexao->affected_rows;

if($linhasAfetadas > 0){
    header("location:gerenciar.php");
} else {
    echo "<strong>Houve um erro ao registrar os itens e categoria!</strong>";
    echo "<a href=gerenciar.php>Voltar para a página anterior</a>";
}

Browser other questions tagged

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