Mia Legaspi Mia Legaspi - 6 months ago 27
PHP Question

Using function to create a connection

I'm trying to create a connection using function in my other php file. So I can access it in every php file. How can I call the function inside my

class
from another php file. What is the proper way creating instance of my function will I put it in the top of my file or inside my class? I try to run my system but the connection won't load.

connection.php

<?php

DEFINE ('host', 'localhost');
DEFINE ('username', 'root');
DEFINE ('password', '');
DEFINE ('database', 'librarysystem');

function getConnection()
{
$myDB = mysqli_connect(host,username,password,database);

if (!$myDB)
{
trigger_error ('Could not connect to MySQL: ' . mysqli_connect_error());
}
else
{
return $myDB;
}
}
?>


Another file where I'm gonna call my function or method.

loginCRUD.php

<?php
error_reporting(0);

require_once ('../connection/connection.php');

$myConnection = getConnection();

class loginCRUD
{
public function readLogin($dbusername,$dbpassword)
{
$statement = $myConnection->prepare("SELECT * FROM loginmodule WHERE loginUsername = ? AND loginPassword = ? LIMIT 1");
$statement->bind_param("ss", $dbusername, $dbpassword);
if($statement->execute())
{
$result = $statement->get_result();
if($result->num_rows)
{
$row = $result->fetch_assoc();
return $row;
}
else
{
return false;
}
}
else
{
return false;
}
}
}
(new loginCRUD)->readLogin($dbusername,$dbpassword);
?>

Answer

There can be at least two possible ways of passing $myConnection to your loginCRUD class.

First is to create $myConnection in a class itself:

class loginCRUD
{
    protected $dbCon;

    public function __construct() 
    {
       $this->dbCon = getConnection();
    }

    public function readLogin($dbusername,$dbpassword)
    {
        $statement = $this->dbCon->prepare("YOUR SQL")
        // other codes
    }
}

(new loginCRUD)->readLogin($dbusername,$dbpassword);

Second is to pass $myConnection as an argument to your class constructor:

class loginCRUD
{
    protected $dbCon;    

    public function __construct($myCon) 
    {
       $this->dbCon = $myCon;
    }

    public function readLogin($dbusername,$dbpassword)
    {
        $statement = $this->dbCon->prepare("YOUR SQL")
        // other codes

    }
}

$myConnection = getConnection();
(new loginCRUD($myConnection))->readLogin($dbusername,$dbpassword);