eatonphil
eatonphil

Reputation: 13682

New to PDO function not doing anything?

Here is my code:

function connect() {
    $pdo = new PDO("mysql:host=localhost;dbname=www","user","pass");
   $xmax = "SELECT MAX(x) FROM headerfooter WHERE site = 'Brighter_Vista'";
   $xresult = $pdo->query($xmax);
   while($row = $xresult->fetch(PDO::FETCH_ASSOC)) {
       print_r($row);
    }
    $ymax = "SELECT MAX(y) FROM headerfooter WHERE site = 'Brighter_Vista'";
   $yresult = $pdo->query($ymax);
   while($row = $yresult->fetch(PDO::FETCH_ASSOC)) {
       print_r($row);
   }
}

I call the function and nothing shows up.

I checked the query in mysql terminal and it does work.

I am new to PDO, what am I doing wrong?

Upvotes: 0

Views: 79

Answers (2)

Ray
Ray

Reputation: 41428

Wrap your query in a try catch block. Chances are the connection is failing quietly.

function connect() {
  try{
      $pdo = new PDO("mysql:host=localhost;dbname=www","user","pass");
      $xmax = "SELECT MAX(x) FROM headerfooter WHERE site = 'Brighter_Vista'";
      $xresult = $pdo->query($xmax);
      while($row = $xresult->fetch(PDO::FETCH_ASSOC)) {
          print_r($row);
      }

      $ymax = "SELECT MAX(y) FROM headerfooter WHERE site = 'Brighter_Vista'";
      $yresult = $pdo->query($ymax);
      while($row = $yresult->fetch(PDO::FETCH_ASSOC)) {
          print_r($row);
      }
   }catch (Exception $e){
      echo $e->getMessage();
      exit;
   }

}

If the exception is thrown, the message indicate where your issue is.

Upvotes: 1

Shoe
Shoe

Reputation: 76240

The function is syntactically correct. Everything seems to be all right and the only problem I could see is related to a problem of PDO trying to connect. Just replace your function with this one:

function connect() {
    try {
        $pdo = new \PDO("mysql:host=localhost;dbname=www","user","pass");
        $xmax = "SELECT MAX(x) FROM headerfooter WHERE site = 'Brighter_Vista'";
        $xresult = $pdo->query($xmax);
            while($row = $xresult->fetch(PDO::FETCH_ASSOC))
                print_r($row);
        $ymax = "SELECT MAX(y) FROM headerfooter WHERE site = 'Brighter_Vista'";
        $yresult = $pdo->query($ymax);
            while($row = $yresult->fetch(PDO::FETCH_ASSOC))
                print_r($row);
    } catch (\PDOException $e) {
        exit($e->getMessage());
    }
}

This function show or prevent errors in case of:

  • any PDO error
  • context in which you are using namespaces

Upvotes: 1

Related Questions