Irfan Irfan - 4 months ago 16
PHP Question

OOP mysqli database functions

I am a beginner in OOP in PHP and I am trying to play with my code. So first thing I wanted to do is to write one basic class with connect and insert functions for database. So my desired situation is this:

-I wanna create on class which will controll connect and insert functions. The problem is, my $connect variable isn't working from another function, so what could I do to make that possible?
You will understand more by the code provided.

<?php

class DB {
protected $dbhost = 'localhost';
protected $dbuser = 'root';
protected $dbpass = '';
protected $dbname = 'newdb';

public function connect()
{
$connect = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);

if($connect->error)
{
echo "Failed to connect";
}
else
{
echo "connected";
}
}

public function insert($name, $second)
{
$insert = "INSERT INTO posts (name, second) VALUES ('$name', '$second')";

if ($connect->query($insert) === TRUE)
{
echo "New record created successfully";
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_connect_error();
}
}
}
require_once 'classes/DB.php';

$db = new DB;

if(isset($_POST['submit']))
{
$name = $_POST['name'];
$second = $_POST['second'];

$db->insert($name, $second);
}

?>


<form method="POST">
Add smth<input type="text" name="name"><br>
Also omg<input type="text" name="second"><br>
<input type="submit" name="submit">
</form>

Answer

Add $connect as a property of your class, so you may reuse it everywhere within the class using $this->connect:

class DB
{
    protected $dbhost = 'localhost';
    protected $dbuser = 'root';
    protected $dbpass = '';
    protected $dbname = 'newdb';
    protected $connect;

    public function connect()
    {
        $this->connect = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);

        if ($this->connect->error)
        {
            echo "Failed to connect";
        }
        else
        {
            echo "connected";
        }
    }

    public function insert($name, $second)
    {
        $insert = "INSERT INTO posts (name, second) VALUES ('$name', '$second')";

        if ($this->connect->query($insert) === TRUE)
        {
            echo "New record created successfully";
        }
        else
        {
            echo "Error: " . $sql . "<br>" . mysqli_connect_error();
        }
    }
}