简体   繁体   English

PHP OOP无法查询mysqli

[英]PHP OOP Cannot Query mysqli

I have been struggling for days to figure how to follow OOP in the following procedure. 我一直在苦苦思索如何在以下程序中遵循OOP。

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. 这是我的Helpers类,这个类包含将在我的webapp中使用的所有常用方法,如插入数据,删除和更新。

<?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 现在我在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(). 调用未定义的方法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."');"; 即: value ('$name');";value ('".$name."');"; which is another method. 这是另一种方法。

Sidenote: value and values are accepted and are both considered as valid syntax in MySQL. 旁注:接受valuevalues ,并且在MySQL中都被视为有效语法。

As per the manual: http://dev.mysql.com/doc/refman/5.6/en/insert.html 根据手册: 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 . 旁注:您现在的代码对SQL注入开放。 Use mysqli with prepared statements , or PDO with prepared statements , they're much safer . mysqli与准备好的语句一起使用,或者将PDO与准备好的语句一起使用它们会更加安全

Change your class as follows. 按如下方式更改课程。 Since you are passing a Connection Object you need to set its con property to the $this->con . 由于传递连接对象,因此需要将其con属性设置为$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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM