0

I'm trying to create a Mysqli to get data from database using OOP. And I can't get any data from the database, and when I check the connection, it returns null

Here's my DatabaseHelper class.

class DatabaseHelper
{

    private $servername;
    private $username;
    private $password;
    private $dbname;

    public function connect()
    {
        $this->servername = "localhost";
        $this->username = "root";
        $this->password = "";
        $this->name = "test";

        $conn = new mysqli($this->servername, $this->username, $this->password, $this->dbname);
        echo '<pre>';
        var_export($conn);
        echo '</pre>';
    }
}

And here's the connection data.

mysqli::__set_state(array(
   'affected_rows' => NULL,
   'client_info' => NULL,
   'client_version' => NULL,
   'connect_errno' => NULL,
   'connect_error' => NULL,
   'errno' => NULL,
   'error' => NULL,
   'error_list' => NULL,
   'field_count' => NULL,
   'host_info' => NULL,
   'info' => NULL,
   'insert_id' => NULL,
   'server_info' => NULL,
   'server_version' => NULL,
   'sqlstate' => NULL,
   'protocol_version' => NULL,
   'thread_id' => NULL,
   'warning_count' => NULL,
))

Is there anything wrong in my code above that makes the connection returns null?

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Josh Adrian
  • 126
  • 1
  • 9
  • 1
    just wondering, what's the point in this class? how it's different from vanilla mysqli? – Your Common Sense Nov 15 '20 at 05:00
  • I'm trying to get data from my table using a class so I just need to call the class and get all the data and reuse that class @YourCommonSense – Josh Adrian Nov 15 '20 at 05:13
  • 1
    but mysqli is *already* a class! why don't you do just `$conn = new mysqli` and then reuse this $conn object all over the way? – Your Common Sense Nov 15 '20 at 05:17
  • you're not getting my point, I'm trying to get data from my table, and store it inside a class, but to that i need to make this connection class so I don't have to re write this connection in every class I make to get data from another table @YourCommonSense – Josh Adrian Nov 15 '20 at 05:21
  • 1
    No, it's you're not getting my point. Instead of this "connection class" you can use just mysqli class to store any data in any class. Mysqli will serve you as well. – Your Common Sense Nov 15 '20 at 05:26
  • Ok, is there any example you can give me, to make me understand what you're saying – Josh Adrian Nov 15 '20 at 05:29
  • 1
    For the class working with a certain table, provide the $conn object as a *constructor parameter* and then assign to a property. **This** is how OOP actually works. See example [here](https://stackoverflow.com/a/43631201/285587). – Your Common Sense Nov 15 '20 at 05:34

0 Answers0