Sonia
Sonia

Reputation: 253

No database selected inside function, what the solution with PDO?

I'm attempting to perform a query inside a function but it return me "No database selected". I regularly have re-initialized the PDO object inside it

$db = "mysql:host=localhost;dbname=my_database";
$pdo = new PDO($db, 'dbname', 'dbpassword');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//some operations.. Works fine!

function sendMail($to)
    {
      $db = "mysql:host=localhost;dbname=my_database";
      $pdo = new PDO($db, 'dbname', 'dbpassword');
      $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

      $qryString="SELECT Codice FROM users WHERE Mail=:mail";
      $qry = $pdo->prepare($qryString);
      $params = array("mail" => $to);
      $qry->execute($params); //won't work
    }

Note that operations on the DB outside the function works fine.

The problem is that the code won't work neither passing the global $pdo object. This is the actual code

 $db = "mysql:host=localhost;dbname=my_database";
 $pdo = new PDO($db, 'dbname', 'dbpassword');
 $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

 sendMail($mail, $pdo)

function sendMail($to, PDO $pdo)
        {
          $qryString="SELECT Codice FROM users WHERE Mail=:mail";
          $qry = $pdo->prepare($qryString);
          $params = array("mail" => $to);
          $qry->execute($params); 
        }

Upvotes: 0

Views: 230

Answers (2)

Your Common Sense
Your Common Sense

Reputation: 158007

Variable scope has absolutely nothing to do with database connection details.
If you have a connection where database selected, the same database will be selected if you are using this connection inside a function.

So, this is a clear case of too localized question, as the problem is obviously of typo-like - connecting to wrong database, misspelling variable name, database name and such.

Unfortunately, regular PHP user has very little knowledge on performing correct, reproduceable experiment to prove their assumption. Instead, they guess the reason by indirect consequences.

You just have to write the code you told us about and see that database is selected all right. And then turn to search for real reason. Full error reporting (E_ALL) often helps a lot.

Upvotes: 3

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48751

Pass the PDO object to the function, because the scope of $pdo is outside the scope of sendMail().

function sendMail(PDO $pdo, $to) {
    $queryString = "SELECT Codice FROM users WHERE Mail=:mail";
    $statement = $pdo->prepare($queryString);
    $params = array("mail" => $to);
    $result = $statement->execute($params);
}

or

function sendMail($to) {
    global $pdo;
    $queryString = "SELECT Codice FROM users WHERE Mail=:mail";
    $statement = $pdo->prepare($queryString);
    $params = array("mail" => $to);
    $result = $statement->execute($params);
}

Upvotes: 0

Related Questions