With the script below I'm trying to add a new user to the user table. I'm new with working with classes and so far I'm not able to get it working. My server is running PHP7.
config.php
<?php
/**
* Database config variables
*/
define("DB_HOST", "localhost");
define("DB_USER", "username");
define("DB_PASSWORD", "12345");
define("DB_DATABASE", "databasename");
?>
connect.php
<?php
class DB_Connect {
// constructor
function __construct() {
}
// destructor
function __destruct() {
// $this->close();
}
// Connecting to database
public function connect() {
require_once '/folder/folder/folder/config.php';
// connecting to mysql
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
// return database handler
return $conn;
}
// Closing database connection
public function close() {
$conn->close();
}
}
?>
If I change the connect function in the connect.php to the function below I get the succes message (Connected successfully) so I think there is no database connection issue:
public function connect() {
require_once '/folder/folder/folder/config.php';
// connecting to mysql
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
}
functions.php
<?php
class DB_Functions {
private $db;
//put your code here
// constructor
function __construct() {
include_once './connect.php';
// connecting to database
$this->db = new DB_Connect();
$this->db->connect();
}
// destructor
function __destruct() {
}
/**
* Storing new device
*/
public function storeUser($name, $userid, $club) {
echo;
// insert user into database
$result = "INSERT INTO users(name, user_id, club_id, created_at) VALUES('$name', $userid, $club, NOW())";
// check for successful store
if ($result) {
// succes
return "Device is added";
} else {
return "Error: Device is not added!" ;
}
}
/**
* Getting all users
*/
public function getAllUsers() {
$result = "select * FROM users";
return $result;
}
}
?>
The script below I made as a test script to run in the browser to add a test user:
<?php
$name = "1234567890";
$userid = "1234";
$club = "09876";
include_once './functions.php';
$db = new DB_Functions();
$res = $db->storeUser($name, $userid, $club);
echo $res;
?>