Mysqli query in function - PHP
Solution 1:
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.
Solution 2:
$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"];
}