[FIXED] Executing mysqli_query inside a function

Issue

I have a list of functions in functions.php. I'm upgrading from Mysql to Mysqli because I just learning Mysql is now depreciated.

I declare my connection in a top levelconnect.php file. The first file is required.

All my functions use mysql_query("QUERY"), which always worked fine. Now I changed all of them to:

$con->query("QUERY") // ($con is my connection variable)

Now I'm getting a

Fatal error: Call to a member function query() on a non-object in C:\wamp\www\PHP\functions.php on line 241

I don't get why I can query if I'm declaring my variable in my whole file. It should be accessible everywhere, I'm just not sure. This has put my website on hold until I can fix this. Here is a sample function from functions.php

function getSiteName()
{
    $row = $con->query("SELECT * FROM siteinfo")->fetch_array();
    return $row["siteName"];
}

My connection:

global $con ;
$con = new mysqli("localhost", "itunes89", "XXXX","projectanvil") or die("Sorry, were having server connection issues. Please try again later.");

Solution

That's a variable scope problem. You need to pass $conn to getSiteName():

function getSiteName($con) {
    $row = $con->query("SELECT * FROM siteinfo")->fetch_array();
    return $row["siteName"];
}

$name = getSiteName($con);

Or using a class with constructor injection:

class MyThing
{
    protected $con;

    public function __construct($con) {
        $this->con = $con;
    }

    public function getSiteName() {
        $row = $this->con->query("SELECT * FROM siteinfo")->fetch_array();
        return $row["siteName"];
    }
}

$obj = new MyThing($con);
$name = $obj->getSiteName();

Throughout the class you can use $this->con to access the connection.



Answered By - MrCode
Answer Checked By - Pedro (sql.easybugfix Volunteer)

Related Posts

Post a Comment