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;
}
?>
You made the connection before doing the
prepare
? Not sending any error message?– Roberto de Campos
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!
– Wel
Problem solved as suggested by Roberto de Campos, had not made the connection previously.
– Wel
accept his answer then
– Math
Wel, in that case you should mark the other answer as accepted, with that green.
– Sergio
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
@Wel, amended answer.
– Roberto de Campos