Question:
I'm starting with PDO. I'm trying to connect to the bank and I can't.
I have the following code
$host = "localhost";
$user = "root";
$pass = "root";
$dbname = "angularDB";
try {
$pdo = new PDO("mysql:host=localhost;dbname=angularDBB"; "root", "root", $opcoes);
$opcoes = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
} catch (Exception $e) {
echo $e->getMessage();
}
return $pdo;
However, no error appears… Not even if I enter a fictitious bank name!
Answer:
Based on the source you posted on github , in this snippet :
$pdo = new PDO("mysql:host=localhost;dbname=angularDBB"; "root", "root", $opcoes);
$opcoes = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
1st Step
First, you must change the order:
$opcoes = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$pdo = new PDO("mysql:host=localhost;dbname=angularDBB"; "root", "root", $opcoes);
Because when you create a PDO instance in the $pdo
variable it tries to know if the $opcoes
variable is defined, and what its values are.
2nd Step
Also in this same part of the code, we have an error when writing the parameters. Where should it be:
$pdo = new PDO ('mysql: host= host_name; dbname= db_name;', 'db_user', 'db_pwd', [...]);
It is like this :
$pdo = new PDO ('mysql: host= host_name; dbname= db_name'; 'db_user', 'db_pwd', [...]);
^
There is one ;
instead of a comma. Remove the ;
it would be enough to fix this line.
So far we have practically solved the problem, but now let's analyze it.
With the modifications made, if we do:
var_dump(conectar());
// Retorna: object(PDO)#1 (0) { }
Which means it didn't have any object returns, that's because we're trying to find out if it returned anything that isn't boolean , you can see that by the curly braces.
Now, if we try again to print the value returned by the function, but this time using echo , and using the cast type method to define the expected return type:
echo((bool)conectar());
// Retorna: 1, equivalente a true
Another observation, is in this part of the code:
print_r($pdo->query('select database()')->fetch());
It is very unlikely that we will get any correct result with this, in an attempt to return all the existing results, because writing the expression all in line, we get an infinite return , see this example, where I used the jogos
table as a base:
while($linha = $pdo->query("SELECT * FROM jogos")->fetch(PDO::FETCH_OBJ)){
echo $linha->nome . "<br/>";
}
In addition to not moving the pointer once, when selecting results in the database, it prints an infinite loop of the first result.
The correct thing would be, first, perform the query, and only then return the results using fetch
, if the objective was to return all the results in the table in use.
$query = $pdo->query("SELECT * FROM jogos");
while($linha = $query->fetch(PDO::FETCH_OBJ)){
echo $linha->nome . "<br/>";
}
For the case of a single result, as it is in your original example, we would do the following:
$pdo->query("SELECT * FROM jogos")->fetch(PDO::FETCH_OBJ)->nome;
// fetch(tipo de retorno)
// nome é o indice que queremos retornar
The complete function would look like this:
function conectar(){
$host = "localhost";
$user = "root";
$pass = "root";
$dbname = "example";
$erro = "";
try {
$opcoes = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$pdo = new PDO("mysql:host=localhost;dbname=example", "root", "root", $opcoes);
} catch (Exception $e) {
$erro = $e->getMessage();
}
if($pdo){
return $pdo->query("SELECT * FROM jogos")->fetch(PDO::FETCH_OBJ)->nome;
// Ou usando o looping while, para retornar todos os resultados
/*
$query = $pdo->query("SELECT * FROM jogos");
while($linha = $query->fetch(PDO::FETCH_OBJ)){
echo $linha->nome . "<br/>";
}
*/
} else {
return $erro;
}
}
// Saída dos resultados
echo conectar();
Still, this function is by far the best practice for instantiating PDO connections, I recommend that you look for a more suitable way to do this.
Some references:
How to properly set up the PDO Connection – SOen