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.