Select with PDO and SQL barring HTML

Asked

Viewed 183 times

2

I am trying to make a Select with PDO and MYSQL, but when I put php code in the middle of my html it does not allow the execution of the rest of the page.

follows the code excerpt:

<select class="emselect">
    <option value="select">selecione</option>
    <?php
    $buscarid=$pdo->prepare("SELECT ID,usuario FROM usuarios ORDER BY ID ASC");
    $buscarid->execute();
    while($linha=$buscarid->fetch(PDO::FETCH_ASSOC)){
        echo "<option value=".$linha["ID"].$linha["usuario"].">".$linha["ID"]." ".$linha["usuario"]."</option>";
    }
    ?>
    </option>
</select>

After trying to do some tests I realized that the problem was in php, but it is not linked to any kind of "open" closure, something that already gave me problem before, so I believe that the connection in the middle of html code is blocking, so what would be the best way to do this? I need while to stay in the same place to list the select items.

  • You made the connection before doing the prepare? Not sending any error message?

  • 1

    He hadn’t touched me! was exactly that, this page was running after logging in, I ended up passing the connection on it because I had already put in the previous, I think I thought that being in the same session would continue, thanks for the help!

  • Problem solved as suggested by Roberto de Campos, had not made the connection previously.

  • accept his answer then

  • Wel, in that case you should mark the other answer as accepted, with that green.

  • he answered me in the comment, the answer he made here does not solve the problem, if he put what said in the comment as answer I will accept it.

  • @Wel, amended answer.

Show 2 more comments

1 answer

3


Apparently missed you make the connection before using the function prepare, you can do it this way:

$conn = new PDO('mysql:host=localhost;dbname=seu_banco_de_dados', 'seu_usuario', 'sua_senha');

Now from the variable $conn which is where your connection is, you run the prepare and assigns its variable $buscarid:

<select class="emselect">
    <option value="select">selecione</option>
    <?php
    $buscarid = $conn->prepare("SELECT ID, usuario FROM usuarios ORDER BY ID ASC");
    $buscarid->execute();
    while($linha=$buscarid->fetch(PDO::FETCH_ASSOC)){
        echo "<option value=".$linha["ID"].$linha["usuario"].">".$linha["ID"]." ".$linha["usuario"]."</option>";
    }
    ?>
</select>

However, this way it will require you to repeat the code to make the connection every time you need to connect to the database. If you need maintenance on your system, you may get a headache. To avoid this code repetition, you can create a class where the connection will be created, so create a new file PHP called conexao.class.php and place the following content:

<?
    class Conexao extends PDO { // Criamos a classe Conexao que estende todas os métodos e propriedades da classe PDO

        private static $instancia; // Criamos uma variável $instancia que é onde a instancia do PDO ficará quando criada

        //Este método abaixo é o construtor, ou seja, ele será executado quando for criada uma nova instancia da nossa classe Conexao.
        public function Conexao($dsn, $username, $password){
            parent::__construct($dsn, $username, $password);//Aqui estamos chamando o método construtor da classe pai que no nosso caso é PDO
        }

        //Este método, será responsável por criar a conexão ou retornar a conexão existente
        public static function getInstance(){
            if (!isset(self::$instancia)){ //Se a variável $instancia não estiver setada, a conexão será criada
                try{
                    //Neste ponto criamos uma instancia da classe Conexao e armazenamos ela dentro da variável $instancia
                    self::$instancia = new Conexao("mysql:host=localhost; dbname=seu_banco_de_dados",
                        "seu_usuario", "sua_senha");
                } catch (Exception $e) { //Em caso de erro ao tentar se conectar será retornada uma string com o erro
                    return "Ocorreu um erro ao conectar!<br />".$e->getMessage();
                }
            }

            return self::$instancia; //Caso der tudo certo será retornada a Conexao criada
        }
    }
?>

Your code to recover users would look like this:

<?
    include_once 'conexao.class.php';
    $conn = Conexao::getInstance();
    if (!is_string($conn)) { //Se a variável $conn não for uma string a conexão foi efetuada com sucesso
        ?>
            <select class="emselect">
                <option value="select">selecione</option>
                <?
                    $buscarid = $conn->prepare("SELECT ID, usuario FROM usuarios ORDER BY ID ASC");
                    $buscarid->execute();
                    while($linha=$buscarid->fetch(PDO::FETCH_ASSOC)){
                        echo "<option value=".$linha["ID"].$linha["usuario"].">".$linha["ID"]." ".$linha["usuario"]."</option>";
                    }
                ?>
            </select>
        <?
    } else {//Caso a variável $conn seja uma string, ela conterá o erro que ocorreu na conexão
        echo $conn;
    }
?>
  • I believe that this is not the problem, so I had noticed the problem is in the execution of PDO, anywhere I put it in the middle of my code, all the code below in html simply does not execute.

  • @Roberto takes a look at the comments of the other reply

  • @Math Thanks for the comment, I just implemented the reply

Browser other questions tagged

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