Adrià Illa Adrià Illa - 4 months ago 10
SQL Question

Can I make a `new mysqli()` into a php class?

I'm trying to connect to mysql database (with mysqli) into a php class. When I do this, by

new mysqli(params)
, I get the


unexpected 'new'


error. How can I do this? My idea is something like this:

<?php


class DbConnection
{
public $conn = new mysqli("localhost","root","","todo");



function RegisterUsers($username, $password, $ip, $name)
{
$stmt = $this->$conn->preapre("INSERT INTO users (Username, Password, ip, Name) VALUES (?,?,?,?)");
$stmt->bind_param("ssss", $username, $password, $ip, $name);
$stmt->execute();
}

}

$dbConn = new DbConnection();
$dbConn->RegisterUsers("a","a","a","a");

?>

Answer

Error here:

public $conn = new mysqli("localhost","root","","todo");

Create connection instance in constructor and modify you code as follow:

class DbConnection
{
    public $conn;

    function __construct()
    {
        $this->conn = new mysqli("localhost","root","","todo");
    }

    function RegisterUsers($username, $password, $ip, $name)
    {
        $stmt = $this->conn->prepare("INSERT INTO users (Username, Password, ip, Name) VALUES (?,?,?,?)");
        $stmt->bind_param("ssss", $username, $password, $ip, $name);
        $stmt->execute();
    }

}

Also you have a typo preapre and do not need $ while using $conn property inside the object

Comments