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);
}