我正在使用Add Query创建PHP OOP连接

时间:2016-05-10 03:23:57

标签: php mysql oop

我是在Java Swing OOP上开发的,所以我对PHP OOP技术有点困惑,它们在逻辑上是相同的但在语法上却不一样。请帮助我,我需要你的专业。谢谢大家。

这是我的index.php

<?php
require_once("DB.class.php");

$db = new DB("localhost", "root", "100510", "findersa_jfph_smart");

$db->select("t1.`sid` AS 'id', t1.`Title` AS 'title', t1.`JobDescription` AS 'content', t1.`Location_City` AS 'city', t1.`SalaryType` AS 'salary',
 t1.`EmploymentType` AS 'working_hours', t2.`CompanyName` AS 'company', t1.`JobRequirements` AS 'requirements', t1.`JobCategory` AS 'category', t1.`activation_date` AS 'date',
 t2.`PhoneNumber` AS 'contact_telephone'","`listings` AS t1
LEFT JOIN `users` AS t2
ON t1.`user_sid` = t2.`sid`","t1.`activation_date` BETWEEN '2016-02-02 00:00:00' AND '2016-05-02 23:59:59' AND t1.active = '1' AND t1.listing_type_sid = '6'
LIMIT 50000");

?>

这是我的DB.class.php

<?php
class DB {

    public $host;
    public $user;
    public $pass;
    public $dbase;

    public function __construct($host, $user, $pass, $dbase) {

        $this->host = $host;
        $this->user = $user;
        $this->pass = $pass;
        $this->dbase = $dbase;

        $conn = new mysqli($this->host, $this->user, $this->pass, $this->dbase);

        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }

         echo "Connected Successfully!";
    }

    public function select($myCols, $myTable, $myQuery) {

        if (!isset($myQuery)) {
            $sql = "select " . $myCols . " from " . $myTable;
        } else {
            $sql = "select " . $myCols . " from " . $myTable . " from " . $myQuery;
        }

        $result = $this->conn->query($sql);

        if ($result->num_rows > 0) {
            return $result;
        } else {
            return "0 results";
        }

        $conn->close();
    }

}


?>

抱歉,我无法获得包装盒中的所有代码。但这是我有一个特殊的错误:

$result = $this->conn->query($sql);

在DB.class.php中。

谢谢。这是我的第一个问题,请耐心等待。

1 个答案:

答案 0 :(得分:1)

在PHP中声明类定义中的变量不是必需的,它更多的是为了可读性。虽然您可以设置public,protected,private和static的定义。

您可以通过使用self实例进行引用,将变量分配给类级别。如果您将其编写为静态类,则可以使用$this->conn = new mysqli();进行引用。

使用当前代码,select方法中的数据库连接不可用,通过$conn = new mysqli();将其分配到类级别可以轻松实现。当变量定义为SideNavigationController.enabledRightPanGesture = false时,它只能被声明它的方法访问。