php - Executing mysqli_query inside a function

284

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 usemysql_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.");
872

Answer

Solution:

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

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.

457

Answer

Solution:

Since you made $con global, to make getSiteName function access it you should write:

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

People are also looking for solutions to the problem: php - Codeigniter tutorial static page.. using Bitnami WAMP

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.