ziko310 ziko310 - 3 months ago 10
PHP Question

Undefined variable: id (GET)

Undefined variable: id, i tested the id by eachoing it and it worked so how it's Undefined

mycontroller

if(isset($_GET['deleteid']))
{
$id = $_GET['deleteid'];
require_once '../model/dsections.php';
$delete = new Dsections("sections");
$delete->deletesec($id);
require_once '../view/vsections.php';



}


model

class Dsections extends cone{

protected $tablename;


public function __construct($tablename)
{

//DB table name.
$this->tablename = $tablename;
//DB connection.
$this->connectTodb();
//Delete function
$this->deletesec($id);

}
public function deletesec($id)
{
// Delete a specific section.
$query = "DELETE * FROM $this->tablename WHERE id = $id ";

if (!$sqli = mysqli_query($this->cxn->connect(),$query)) {


throw new Exception("Error Processing Request");

}
}


}
the error at this line in mymodel
$this->deletesec($id);

Answer

in your Dsection constructor you call $this->deletesec($id); on $id which is undefined :)

  public function __construct($tablename)
  {

      //DB table name.
      $this->tablename = $tablename;
      //DB connection.
      $this->connectTodb();
      //Delete function
      $this->deletesec($id); // <--------- this line here $id is not defined here

  }

The constructor must look like:

  public function __construct($tablename)
  {

      //DB table name.
      $this->tablename = $tablename;
      //DB connection.
      $this->connectTodb();
  }

Without delete function because you are calling it anyway later!

OR you can simply add the $id to the constructor like this:

  public function __construct($tablename,$id)
  {
      //DB table name.
      $this->tablename = $tablename;
      //DB connection.
      $this->connectTodb();
      //Delete function
      $this->deletesec($id);
  }

BUT this is not recommended, because it violates the most important software engineering principle (IMHO) which is the Single Responsibility Principle