CoderDude Twodee CoderDude Twodee - 1 year ago 74
MySQL Question

Custom database connection not working in php

I have this class that would establish a connection to the MySQL database in php. But there seems to be something wrong with it, and clearly I am making a mistake.

This is the class:

class dbConnection {

public $CONN;

public function __construct() {
$dbservername = "localhost";
$dbusername = "test";
$dbpassword = "pass";
$dbname = "dbtest";

// Create connection
$this->CONN = new mysqli($dbservername, $dbusername, $dbpassword, $dbname);

// Check connection
if ($this->CONN->connect_error) {
die("Connection failed: " . $CONN->connect_error);
return $this->CONN;

public function close() {

This is calling the class to perform an

$conn = new dbConnection();
$stmt = $conn->prepare("INSERT INTO tablename (stuff1, stuff2, stuff3) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $val1, $val2, $val3);

// set parameters and execute
$val1 = "val1";
$val2 = "foo";
$val3 = "bar";

The error showing is:

Fatal error: Uncaught Error: Call to undefined method dbConnection::prepare() in /var/www/index.php:7 Stack trace: #0 {main} thrown in /var/www/index.php on line 7

This works if I set up a function inside the class and call it instead of the constructor, but I would like to have it done with the constructor itself.
How do I establish this?

Answer Source

You can create a prepare method for the dbConnection class:

public function prepare($query) {
    return $this->CONN->prepare($query);

and your current code would work. Tested it on my machine and it does work.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download