I am trying to make a database connection in PHP using two different classes. There is an error in my object creation:
Error: Parse error: syntax error, unexpected '$obj' (T_VARIABLE), expecting function (T_FUNCTION)
The error occurs on this line: $obj = new UserController();
This is my Connection
class:
class Connection
{
public $servername = "localhost";
public $username = "root";
public $password = "";
public $dbname = "web-portal";
function database (){
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
return $conn;
} else {
return $conn;
}
}
}
This is my UserController
class:
class UserController extends Connection {
$obj = new UserController();
//$obj->database();
function getUser ($userId) {
// Sql query to select record from user table
$sql = "SELECT * FROM User where user_id = ".$userId;
//Excute sql query
$result = $conn->query($sql);
//If record exists
if ($result->num_rows > 0) {
// output data of each row
$row = $result->fetch_assoc();
$conn->close();
return $row;
} else {
//If no record exists return row 0
$row = 0;
return $row;
}
}
}
Some general guidance:
UserController
is not a Connection
, so this is not a good inheritance - a UserController
should inherit from Controller
or something similar. $result = $conn->query($sql)
you probably want $this->database()->query($sql)
. $conn
is not available to you anyway. You will need to do $obj = new UserController()
but this would belong in another file, something like this:
require_once 'Connection.php'; require_once 'UserController.php'; $controller = new UserController(); $row = $controller->getuser(1); print_r($row);
You may find that a good approach is to work through some good tutorials on the web - it may be faster in the long term than struggling on a project that is not guided.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.