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 required.
Anyway back to the point all my functions use mysql_query("QUERY") and that always worked fine. Now I changed all the 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.
So 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.");
Thanks guys! :D My site where I'm having this error
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.
$con = new mysqli(
"localhost",
"itunes89",
"XXXX",
"projectanvil"
);
Will not return null or false on failure.
You should check value of
mysqli_connect_errno()
After connection to verify that $con is valid server connection.
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"];
}
Do you defind for $con object
<?php
// connect to the server
$conn = new mysqli('localhost', 'root', 'pass', 'dbname');
// check connection
if (mysqli_connect_errno()) {
exit('Connect failed: '. mysqli_connect_error());
}
?>