Reputation: 173
I am having this:
$db_hostname = 'localhost';
$db_username = 'root';
$db_password = '';
$db_database = 'publications';
saved as connection.php
but i cant inerhit it's variables in this one:
namespace form;
include_once "Form.php";
include_once "connection.php";
class login extends Form
{
public function showLoginfrom()
{
echo '<form name="loginform" method="get">';
$login = new Form();
$login->AddText('username','Your username');
$login->AddPassword('password','','Your password');
$login->SubmitButton('Login');
echo "</form>";
}
public function executeLogin()
{
$connection = new \mysqli($db_hostname,$db_username,$db_password,$db_database);
$username = ($_GET["username"]);
$password = ($_GET["password"]);
$query ="SELECT * FROM users WHERE username= '$username' AND password= '$password'";
$result = $connection->query($query);
if (mysqli_num_rows($result)== 1)
{
echo "Welcome";
}
else
{
echo "Login failed";
}
}
I know that my code is unsafe, i am just experimenting. Its my first php program.
Upvotes: 1
Views: 90
Reputation: 14984
Another way to do it is using a class w/ static members. Something like:
class Config {
static public $mysqli;
static public $dbCredentials = [];
}
include('connection.php');
Config::$dbCredentials['host'] = $db_hostname;
// and repeat for the others
//optional, extra step:
Config::$mysqli = new \mysqli(...);
Then to use, you can do:
public function executeLogin()
{
$connection = new \mysqli(\Config::$dbCredentials['host'], ..);
//or
$connection = \Config::$mysqli;
// do other stuff
}
Other notes/alternatives:
config
class in connection.php
and doing that setup
from there. public static
getConnection()
) to get the mysqli connection (probably use a singleton)public static getDbHost()
)executeLogin
receive a mysqli
object, which would be passed from the calling code.Upvotes: 0
Reputation: 11365
For example;
public function executeLogin($db_hostname,$db_username,$db_password,$db_database)
{
$connection = new \mysqli($db_hostname,$db_username,$db_password,$db_database);
And then call the executeLogin()
method with those variables in the current scope.
Two ways you can inject them to make properties. The first is exactly the same as above put in the __construct()
method.
Another way is to include the files in the __construct()
method and set them as properties. For example
private $arrDbDetails = array();
public function __construct() {
include_once "connection.php";
$this->arrDbDetails = array(
'host' => $db_hostname,
'user' => $db_username,
'pass' => $db_password,
'db' => $db_database
);
You can then access them with $this->arrDbDetails['host']
, for example, in your executeLogin()
method.
$connection = new \mysqli($this->arrDbDetails['host'],$this->arrDbDetails['user'],$this->arrDbDetails['pass'],$this->arrDbDetails['db']);
You can also define
the values and have them in the global scope.
define('DB_USERNAME', 'my_mysql_user');
And then call them as regular constants in your method.
Upvotes: 1