I have a working script, but I want to use static method in my class.
There is a whole bunch of functions I use
but I have to use database class handle
as a 'global' in every function to be able to call the class.

I want to make the method 'querySQL' static.
And so I would be able to call it without using 'global'.

I am certain there is a way. I would be glad to get help
to modify my script.
If it works from one function, it will work from all other functions.

Here is what I got. The database class:

class Database extends PDO
{
    public function __construct($dsn, $dbuser = '', $dbpass = '')
    {
        try{
            parent::__construct($dsn, $dbuser, $dbpass);
        } catch (PDOException $e) {
            exit('PDOException: '.$e->getMessage());
        }
    }

public function querySQL($sql)
{
	$result = $this->query($sql);
	if($result === false) {
		echo $this->errorInfo()[2].'<br>';
		exit($sql);
	}
	return $result;
}
}

And the function that uses the database class:

function getPasswordHashById($id)
{
	global $pdo;

$sql = "SELECT passkey FROM users WHERE id=${id};";
$result = $pdo->querySQL($sql);
return $result->fetchColumn();
}

require('Database.php');
$pdo = new Database('sqlite:data/sqlitedata.db3');

echo getPasswordHashById(1);

    A better bet is to pass the created database object as a parameter to the function that needs it. I also recommend using prepared statements to avoid the SQL injection security hole you currently have in this set-up.

      And perhaps many of these functions that use the database are pieces of an object that could then take the database connection as one of its properties.

        Write a Reply...