如何在类函数中调用连接

时间:2017-12-09 05:56:50

标签: php ajax mysqli

我在__construct()中建立连接它是正常工作但是当我在类的其他函数中调用this->con变量时。它不起作用。 我在数据库中插入数据,但数据在insertUserData()打印正确查询时未插入数据库。

Class RP_Common {

    private $_host = 'localhost';
    private $_username = 'root';
    private $_password = '12345';
    private $_database = 'shipment';

    protected $con;

    public function __construct()
    {
        if (!isset($this->con)) {

            $this->con = new mysqli($this->_host, $this->_username, $this->_password, $this->_database);

            if (!$this->con) {
                echo 'Cannot connect to database server';
                exit;
            }            
        }    

        return $this->con;
    }

    /**

    for inserting user_data
    */

    public function insertUserData($username,$usermobile,$useremail,$userpassword){

        //echo $this->con;

         echo $query="insert into user_table(user_name,user_mobile,user_email,user_password) values('$username',$usermobile,$useremail,$userpassword) ";

        $res=mysqli_query($this->con,$query);

        if($res){
            echo "data inserted successfully";
        }

    }

2 个答案:

答案 0 :(得分:0)

你应该使用准备好的陈述来避免讨厌的引用问题。

$stmt = $this->con->prepare("INSERT INTO user_table(user_name, user_mobile, user_email,user_password) VALUES (?, ?, ?, ?)");
$stmt->bind_param("ssss", $username, $usermobile, $useremail,$userpassword);
if($stmt->execute() === true){
 echo 'Data Successfully saved';
} else {
 echo $this->con->error;  
}

也不要以明文保存密码。这是非常不安全的。使用php password_hash()password_verify()

答案 1 :(得分:0)

user_tablevalues

后需要一个空格
INSERT INTO user_table (user_name,user_mobile,user_email,user_password) values ('$username',$usermobile,$useremail,$userpassword);

要查看查询出了什么问题,您可以使用mysqli_error($conn)

if($res){
  echo "data inserted successfully";
}else{
  echo mysqli_error($this->con);
}