1

I have been struggling for days to figure how to follow OOP in the following procedure.

Here is my connection class which handles my connection to the database.

<?php
class Connection{
    public $con = null;
    public function __construct(){
        return $this->con = new mysqli("127.0.0.1:3306", "root", "root", "tester");
    }

}
?>

And here is my Helpers Class, this class contains all the common methods that will be used in my webapp like Insert data , delete and update.

<?php 
class Helpers{
    public $con = null;
    public function __construct($connection){
        $this->con = $connection;
    }

    public function register($name){
        $con = $this->con;
        $sql = "insert into name(Name)value($name);";
        $con->query($sql);
    }
}
?>

Now I call them like this in my register.php

<?php
require "Connection.php";
require "Helpers.php";

$connection = new Connection();
$Helpers = new Helpers($connection);

$Helpers->register("Keannu");
?>

But I am getting the following error:

Call to undefined method Connection::query().

What did I do wrong?

Shaiful Islam
  • 7,034
  • 12
  • 38
  • 58

2 Answers2

4

In addition to the already given answer, strings in values need to be wrapped in quotes.

I.e.: value ('$name');"; or value ('".$name."');"; which is another method.

Sidenote: value and values are accepted and are both considered as valid syntax in MySQL.

As per the manual: http://dev.mysql.com/doc/refman/5.6/en/insert.html

INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
    [INTO] tbl_name
    [PARTITION (partition_name,...)] 
    [(col_name,...)]
    {VALUES | VALUE} ({expr | DEFAULT},...),(...),...

Sidenote: Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements, they're much safer.

Community
  • 1
  • 1
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
-1

Change your class as follows. Since you are passing a Connection Object you need to set its con property to the $this->con.

<?php 
class Helpers{
    public $con = null;
    public function __construct($connection){
        $this->con = $connection->con;
    }

    public function register($name){
        $con = $this->con;
        $sql = "insert into name (Name) values ($name);";
        $con->query($sql);
    }
}
Yasitha
  • 2,233
  • 4
  • 24
  • 36