-1

I'am trying to call the variable $conn in a method in my function. The variable contains PDO, but it's outside the scope. How would I be able to use it inside the function. Ive tried using GLOBALS but that doesn't seem to work like it does with normal variables. Also I've tried passing it with the function but that doesn't work either.

The SQL works and is tested and if I call $conn->exec() outside of the function it works as well.

class Friend{
    public $firstName;
    public $lastName;
    public $sql;
    public $conn;

    function __construct($firstName, $lastName, $conn){
        $this->firstName = $firstName;
        $this->lastName = $lastName;
        $this->conn = $conn;
    }

    public function create(){
        $this->sql = "INSERT INTO vrienden (Voornaam, Achternaam) VALUES ('$this->firstName', '$this->lastName')";
        // echo $this->sql;
        $stmt = $this->sql;
        // Hieronder het daadwerkelijke uploaden van de vriend.
        echo $stmt;

        $conn->exec($this->stmt);
    }
}

2 Answers2

2

You have an error in your create method. $conn->exec should be $this->conn->exec Also you are using $this->stmt that is not define, have to update it to $stmt

public function create(){
        $this->sql = "INSERT INTO vrienden (Voornaam, Achternaam) VALUES ('$this->firstName', '$this->lastName')";
        // echo $this->sql;
        $stmt = $this->sql;
        // Hieronder het daadwerkelijke uploaden van de vriend.
        echo $stmt;

        $this->conn->exec($stmt);
    }

Please note that you should use prepare statements and sanitize user input to eliminate any SQL injection attacks.

To make your code more secure here is a more detailed example.

public function create(){
    $sql = "INSERT INTO vrienden (Voornaam, Achternaam) VALUES (:name, :lastname)";
    $preparedQuery = $this->conn->prepare($sql);
    $preparedQuery->execute(array(
        ":name" => $this->firstName,
        ":lastname" => $this->lastName
    ));
}
Vidal
  • 2,605
  • 2
  • 16
  • 32
-2

Inside the scope of a function block, when you only write $conn->, it is trying to refer to a localized variable within that block. You need to reference the class property instead.

$this->conn->exec($stmt);

You can learn more about variable visibility in OOP here: https://www.php.net/manual/en/language.oop5.visibility.php

Jeremy Harris
  • 24,318
  • 13
  • 79
  • 133