Matheus Silva Matheus Silva - 4 months ago 20
PHP Question

Undefined variable PDO Connection

I have a separate file that contains the PDO connections i need.

this is the setConnection File.

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


i'm trying to use this connection inside a class in other file, so i included it.

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


I'm getting "Undefined variable at line 12 ($Poll->....).

I have it defined in setConnections, what i'm doing wrong?

More code to help.



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

Answer

You defined the PDO object $Poll at global scope inside setConnections.php, but it is not in scope anywhere inside your question class. You will need to place $Poll in scope either by passing it as a parameter to functions that use it, or by setting it as a property of the question class objects. I would use the property method, passing it to the constructor. This is known as dependency injection.

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

The other method would be to pass it explicitly to the insere() method:

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

In the comments you mentioned storing the connection "universally". That is achievable using the global keyword inside your classes, in a constructor for example, but not recommended.

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

Instead, it is better to pass the connection once to the constructor and access it as a property inside your classes.