PDO connection does not give error, nor with dummy bank

Asked

Viewed 824 times

3

I’m starting with PDO. I’m trying to connect with 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... even if I put a fictitious bank name!

  • Glad you started with PDO. Remove those lines with mysql_*, add this in the builder. $opcoes = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION); new PDO(...., "root", $opcoes);

  • dbname:angularD has that : really? should be a =, dbname=angularD

  • Telvez (and I said maybe...) the problem is in the syntax try this way $Pdo = new PDO( 'mysql:host=localhost;dbname=dbname:angularDB', 'root', 'root' );

  • @rray, look at the changes I made to the code in the post... I made the changes, I just invented a name for the bank and even then, no error is displayed on the screen.

  • Have you tried doing debug ? var_dump($pdo), and see what comes back. And what you’re using is a function ?

  • Even with var_dump($Pdo) nothing appears.

  • Pass the full script, so we can understand what the problem is.

  • Gustavo, just one exercise: read only the title of this question, can you see any meaning? Neither do I... Please, gives a fancy on this, it costs very little to write a descriptive title of the problem, being that "problem with X" is a bad title :P

  • @Brasofilo, only you and Edilson did not understand my problem. And I describe my problem in the post itself! Your comment was totally unnecessary.

  • 1

    I didn’t even look at your problem, I just looked at the title. It’s the title of your question that appears on the first page. If you want to attract the attention of people with know-how, Priche in the title, if not, all right, no problem. . . . Ah, yeah, a descriptive title helps other people who are having the same problem find the solution.

  • title suggestion: Conexão com PDO não dá erro, nem com banco ficticio

  • Pronto @brasofilo, I changed the title

  • @Edilson, I put my code in git https://github.com/GugaSevero/PDO

  • There’s the answer to your problem.

  • 1

    Just to clarify, I try to attack content problems, and the more professional I think the person is more direct I will be; attacking people is trolling and is not my thing :)

Show 10 more comments

2 answers

1

The problem to be your dsn that is incorrect dbname:angularDB should be dbname=angularDB, the problem is that the connection failure does not throw an exception so it will never be sent to the catch block even forcing the error handling like Exception.

$opcoes = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$pdo = new PDO("mysql:host=localhost;dbname:angularDB"; "root", "root", $opcoes);
  • Nothing @rray, even with these lines no error appears... I know that if the connection is OK no error will appear, but I’m putting a fictitious bdname, because if error is pq the thing ta working and I only have to adjust the name of the bank

  • And not to think it’s the version problem with my php hehehee PHP Version 5.6.7

  • @Gustavosevero when you try to run some query that error appears?

  • @Gustavosevero try to do this see what happens, print_r($pdo->query('select database()')->fetch());

  • I’ll put my codes in git and leave the link here.

  • @Gustavosevero blz does this

  • follow the link to git... https://github.com/GugaSevero/PDO

  • I’m thinking the problem is in Try catch... I don’t have to enable Try catch in php?

  • @Gustavosevero, sometimes the constructor does not throw exception or error.

  • @Gustavoseveryour code should look like this: http://pastebin.com/NYT0xp5M

  • I checked the code you sent and nothing appeared on the screen, do you believe? I find it very strange! Nothing works!

  • @Gustavosevero, if you put the name of one that does not exist it returns an Exception, if you put a user that does not exist tbm. anything try to re-install php xD or test on another machine. Ta kinda weird

Show 7 more comments

1


Based on the source that you posted on github, in this passage :

$pdo = new PDO("mysql:host=localhost;dbname=angularDBB"; "root", "root", $opcoes);
        $opcoes = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);

First Step

First, one 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 an instance of PDO in the variable $pdo she tries to know if the variable $opcoes is defined, and what are its values.

2nd Step

Still in this same part of the code, we have an error in the writing of the parameters. Where it should be:

$pdo = new PDO ('mysql: host= host_name; dbname= db_name;', 'db_user', 'db_pwd', [...]);

It’s like this :

$pdo = new PDO ('mysql: host= host_name; dbname= db_name'; 'db_user', 'db_pwd', [...]);
                                                         ^

There is a ; instead of a comma. Remove the ; would be enough to correct this line.

So far we have practically solved the problem, but now let’s review.

With the modifications made, if we do:

var_dump(conectar());
// Retorna: object(PDO)#1 (0) { } 

Which means there was no object return, which is why we’re trying to figure out if any that aren’t returned Boolean, You can see that by the braces.

Now, if we try to print again the value returned by the function, but this time using the echo, and using the method cast type 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 from this, in an attempt to try to return all the existing results, because by writing the entire expression in line, we get a infinite return, see in this example, where I used the table jogos as a basis:

while($linha = $pdo->query("SELECT * FROM jogos")->fetch(PDO::FETCH_OBJ)){
            echo $linha->nome . "<br/>";    
        }

In addition to not moving the pointer once, during the selection of results in the database, prints looping infinite of the first result.

The correct would be to first perform the query, and only then return the results using the fetch, if the goal was to return all 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 full 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 connections PDO, I recommend you look for a more appropriate way to do so.


Some references:

How to properly set up a PDO Connection - Soen

PDO PHP Class - Culttt

PDO - PHP.net

  • print_r($pdo->query('select database()')->fetch()); resume only one line and not an infinite loop. The while example in the answer is another context.

  • Oh okay, my mistake, I’ll be editing soon.

  • 1

    @Edilson, I followed his tips, until part of step 2. I put var_dump(connect()); and a message appeared on the screen... Finally... The warning was that the bank does not exist. Now I will put the right bank.

  • 1

    CLOSED!!!! Object(PDO)#1 (0) { }

  • Good, anything, just be in charge here. Good luck.

Browser other questions tagged

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