私信  •  关注

Arjun Singh

Arjun Singh 最近创建的主题
Arjun Singh 最近回复了
5 年前
回复了 Arjun Singh 创建的主题 » 无法访问php mysqli连接对象属性

DB 类构造函数首先应该设置凭据属性( db_host, db_user, db_pass, db_name 和呼叫 connection 方法 连接

class DB {

    public $con;

    function __construct()
    {
        $this->con = new connection();
        $this->con->db_host = HOST; // replace HOST
        $this->con->db_user = DB_USERNAME; // replace DB_USERNAME
        $this->con->db_pass = DB_PASSWORD; // replace DB_PASSWORD
        $this->con->db_name = DB_NAME; // replace DB_NAME
        $this->con->connection();
    }

    function insertQuery($table, $data_array){ 

        $fields = " (";
        $values = " VALUES (";
        $x = 0;
        $y = 0;

        foreach ($data_array as $key => $value) {

            $fields.= $key;
            $values.= "'".addslashes($value)."'";

            if(sizeof($data_array)-1 != $x){
                $fields.= ",";
                $values.=",";
            }
            else{
                $fields.= ")";
                $values.=")";
            }
            $x++;
        }

        $sql = "insert into ".$table.$fields.$values;

        if (!$this->con->query($sql) === TRUE) {
            return "Error: " . $sql . "<br>" . $this->con->error;
        }
        else {
            $last_id = $this->con->insert_id;
            return $last_id;
        }
    }
 }