Kristaps Gaidulis Kristaps Gaidulis - 4 months ago 37
SQL Question

PHP OOP query() error - Call to undefined method connection::query()

Im trying to insert data into mysql database.
I have class connection

class connection{
function __construct(){
$servername = 'localhost';
$username = 'root';
$password = '';
$database='products2';

// Create connection
$conn = new mysqli($servername, $username, $password,$database);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
return false;
}else{
echo "succesful connection!</br>";
$this->query=$conn;
return true;
}
}
}


And another class in witch I try to insert data into database(i try to do this in __construct of that class)

$sql="INSERT INTO products (name,price,category,f_material,f_size) VALUES ('nosaukums','cena','kategorija,'materials','izmers')";
$db=new connection();
$result=$db->query($sql);


However I get this errror:


Fatal error: Call to undefined method connection::query() in ....

Answer

In order to use the query (from mysqli class) method you need to create a new method public function query() {}. This method will be able to use the mysqli method. In the end, you will be able to acheive the same result but by applying 'query' on your own object ($db) like so $result = $db->query($sql);

Here's the class :

<?php

class connection{

  // define a variable for the database connection
  private $conn;

  // when an instance of 'connection' class is created a connection is made through mysqli
  public function __construct()
  {
    $servername = 'localhost';
    $username = 'root';
    $password = '';
    $database='products2';

    // the connection is stored inside the private variable
    $this->conn = new mysqli($servername, $username, $password,$database);

    // Check connection
    if ($this->conn->connect_error) {
        die("Connection failed: " . $this->conn->connect_error);
        return false;
    } else{
        echo "succesful connection!</br>";
        return true;
    }       
  }

  // method used to send a query to database
  public function query($sql)
  {
    // here you use the connection made on __construct() and apply the method query. Basically we are using inside our method (called query) a method (call query too) from the mysqli class
    $this->conn->query($sql);
    return true;
  }

}

Calling the method :

<?php

    // prepare the SQL request
    $sql = "INSERT INTO products (name,price,category,f_material,f_size) VALUES ('nosaukums','cena','kategorija,'materials','izmers')";

    // create a new instance of the class connection
    $db = new connection();

    // run the method $sql on the newly created instance $db
    $result = $db->query($sql);