user3406014
user3406014

Reputation: 19

OOP in PHP - "__construct" connection

Hey guys i am new to OOP and i am wanting to run two functions both requiring the same connection. I am struggling to declare the $mysqli variable in a way which will allow it to be used by both functions. I would rather just use the one as i will be adding many many more functions later. Any help greatly appreciated.

the error message i am receiving is;

Notice: Undefined variable: mysqli in C:\Users\PC\Documents\XAMPP\htdocs\test.php on line 13

<?php
class OOP 
{
function __construct(){
$mysqli = new mysqli('localhost', 'c3337015', 'c3337015', 'iitb');
if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
        }
    }

function getMember(){
        $stmt = $mysqli->prepare("SELECT First_Name FROM forum members");
        $stmt->execute();
        $stmt->store_result();
        $stmt->bind_result($First_Name);

        while ($row = $stmt->fetch()) {
        echo $First_Name;
        }

}
function getForum(){
        $stmt = $mysqli->prepare("SELECT ForumTitle FROM forum");
        $stmt->execute();
        $stmt->store_result();
        $stmt->bind_result($ForumTitle);

        while ($row = $stmt->fetch()) {
        echo $ForumTitle;
        }

}

}

Upvotes: 1

Views: 203

Answers (2)

lin
lin

Reputation: 18392

<?php
/**
 * My file
 * @author yourname
 *
 */
class OOP {

    /**  ============ class vars  ============ **/

    /**
     * DocBloc comment
     * @var mysqli
     */
    private $mysqli = null;



    /** ============ class methods ============ **/

    function __construct() 
    {

        $this->mysqli = new mysqli ( 'localhost', 'c3337015', 'c3337015', 'iitb' );

        if (mysqli_connect_errno ()) {
            printf ( "Connect failed: %s\n", mysqli_connect_error () );
            exit ();
        }
    }


    /*
     * DocBloc
     */
    function getMember() 
    {
        $stmt = $this->mysqli->prepare ( "SELECT First_Name FROM forum members" );
        $stmt->execute ();
        $stmt->store_result ();
        $stmt->bind_result ( $First_Name );

        while ( $row = $stmt->fetch () ) {
            echo $First_Name;
        }
    }


    /*
     * DocBloc
     */
    function getForum() 
    {
        $stmt = $this->mysqli->prepare ( "SELECT ForumTitle FROM forum" );
        $stmt->execute ();
        $stmt->store_result ();
        $stmt->bind_result ( $ForumTitle );

        while ( $row = $stmt->fetch () ) {
            echo $ForumTitle;
        }
    }
}

Upvotes: 0

Chris Forrence
Chris Forrence

Reputation: 10094

You're declaring $mysqli in your constructor, but it's not a class variable. You can simply add it as a class variable:

class OOP {
    private $mysqli;
    ...

Then any time you want to access the variable, replace $mysqli with $this->mysqli.

Upvotes: 2

Related Questions