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?
In addition to the already given answer, strings in values need to be wrapped in quotes.
Ie: 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},...),(...),...
For more information on string literals, visit
https://dev.mysql.com/doc/refman/5.0/en/string-literals.html
Checking for errors in the query also would have signaled the syntax error.
http://php.net/manual/en/mysqli.error.php
Sidenote: Your present code is open to SQL injection . Use mysqli
with prepared statements , or PDO with prepared statements , they're much safer .
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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.