dqjcb132285 2013-11-01 10:28
浏览 68
已采纳

内部功能没有选择数据库,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); 
        }
  • 写回答

2条回答 默认 最新

  • dsghpgmay31938863 2013-11-01 10:34
    关注

    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);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里