未定义的变量PDO连接

时间:2015-08-02 16:22:30

标签: php pdo

我有一个单独的文件,其中包含我需要的PDO连接。

这是setConnection文件。

$Poll = new PDO("mysql:host=localhost;dbname=polls", "root", "", );

我试图在其他文件的类中使用此连接,所以我将其包含在内。

include_once "setConnections.php";
.
.
.
$Poll->query("....");

我在第12行获得了未定义的变量($ Poll-> ....)。

我在setConnections中定义了它,我做错了什么?

更多代码可以提供帮助。

include_once "setConnections.php";
class question{
    private $id_poll;
    private $title;
    public function __construct($title, $id_poll){
        $this->title = $title;
        $this->id_poll = $id_poll;
    }
    public function insere(){
        the message is saying the error is here $Poll->prepare("INSERT INTO perguntas (id_poll, pergunta) VALUES (?,?)");
        $a->bindParams(1, $this->id_poll);
        $a->bindParams(2, $this->title);
        $insert = $a->execute();
        if($insert >0){
            return true;
        }else{
            return false;
        }
    }

2 个答案:

答案 0 :(得分:3)

您在$Poll内的全局范围内定义了PDO对象setConnections.php,但它不在question类内的任何位置。您需要将$Poll放在作用域中,方法是将其作为参数传递给使用它的函数,或者将其设置为question类对象的属性。我会使用属性方法,将其传递给构造函数。这称为依赖注入

include_once "setConnections.php";

class question{
    private $id_poll;
    private $title;
    // Add a new property for the PDO object
    private $connection;

    // Pass it to the constructor
    public function __construct($title, $id_poll, $connection){
        // Set the property
        $this->connection = $connection;
        $this->title = $title;
        $this->id_poll = $id_poll;
    }
    public function insere(){
        // Now use the connection property inside the class.
        $this->connection->prepare("INSERT INTO perguntas (id_poll, pergunta) VALUES (?,?)");
        $a->bindParams(1, $this->id_poll);
        $a->bindParams(2, $this->title);
        $insert = $a->execute();
        if($insert >0){
            return true;
        }else{
            return false;
        }
    }

另一种方法是将其明确传递给insere()方法:

    public function insere($connection){
        // Now use the connection property inside the class.
        $connection->prepare("INSERT INTO perguntas (id_poll, pergunta)VALUES (?,?)"); 
        // etc...
    }

在评论中提到存储连接“普遍”。这在你的类中是可实现的using the global keyword,例如在构造函数中,但不推荐。

// This is not recommended.
public function __construct() {
  global $Poll;
  $this->connection = $Poll;
}

相反,最好将连接一次传递给构造函数,并将其作为类中的属性进行访问。

答案 1 :(得分:0)

创建PDO的新实例时,您是否有任何错误处理机制?

try {
    $dbh = new PDO("mysql:host=localhost;dbname=polls", "root", "", );
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

如果出现问题,您将看到该消息并知道问题所在。

相关问题