【问题标题】:PHP PDO - Using Constant variable undefined when instantiating PDO objectPHP PDO - 实例化 PDO 对象时使用未定义的常量变量
【发布时间】:2015-12-31 14:11:19
【问题描述】:

我在 Windows 7 上使用 XAMPP 3.2.1 使用 PDO,我在使其工作时遇到问题,即使它在我的共享托管服务器。

settings.php

<?php
define('DB_NAME', 'testdb'); //DB Name
define('DB_HOST', 'localhost'); //DB host
define('DB_USER','root'); //DB user
define('DB_PASSWORD', ''); //DB users password
?>

db.php

<?php

require_once("settings.php");

$db = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset=utf8',      DB_USER, DB_PASSWORD);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

?>

output.php

<?php

require_once("db.php");

function outPutPosts(){
    return $db->query("select * from replies limit 35"); <-- this line
}

?>

它呈现的错误:

注意:未定义变量:db in C:\xampp\htdocs\schoolplatform\output.php 第 10 行

致命错误:在 null 上调用成员函数 query() C:\xampp\htdocs\schoolplatform\output.php 第 10 行

任何帮助将不胜感激:)

【问题讨论】:

标签: php mysql pdo


【解决方案1】:

这个问题是因为 $db 不能直接在函数内部访问。您可以使用 global 关键字在函数内部访问它,如下所示:

function outPutPosts(){
 $db= $_GLOBAL['db'];
 return $db->query("select * from replies limit 35"); 
}

【讨论】:

    【解决方案2】:

    db.php 内部

    <?php
    
    require_once("settings.php");
    
    function getConnection() {
           global $db;
           $db = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset=utf8',      DB_USER, DB_PASSWORD);
           $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
           return $db;
    }
    ?>
    

    然后输出.php

    <?php
    
    require_once("db.php");
    
    function outPutPosts(){
        getConnection();
    
        return $db->query("select * from replies limit 35"); 
    }
    
    ?>
    

    【讨论】:

      【解决方案3】:

      您需要在以后的函数中定义变量$db,如下所示:

       <?php
      
          require_once("db.php");
      
          function outPutPosts(){
              $db = getConnection(); // define the variable $db here
      
              return $db->query("select * from replies limit 35"); 
          }
      
      ?>
      

      【讨论】:

        猜你喜欢
        • 2016-09-02
        • 2016-04-07
        • 2013-11-30
        • 2016-10-18
        • 2023-03-03
        • 2023-01-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多