Passing a PDO MySQL connection into a PHP function can easily be done, simply by assigning global to the PDO connection variable unless you want to be repeating the connection inside every function.
Using a global variable for the MySQL connection actually isn’t insecure its just rather opening up to issues if you re assign that variable elsewhere.
When there is another way to do something that can prevent these small issues you should take it. I myself are an avid user for a global connection variable in functions but i am changing that.
<?php
function db_connect()
{
$host = '';
$db_name = '';
$db_user = '';
$db_password = '';
$db = "mysql:host=$host;dbname=$db_name;charset=utf8mb4";
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC);
return new PDO($db, $db_user, $db_password, $options);
} Just like that you can pass the PDO connection through to a variable like:
<?php
function get_data()
{
$db = db_connect();
$select = $db->prepare("SELECT data FROM `table`;");
$select->execute();
while ($row = $select->fetch(PDO::FETCH_ASSOC)) {
///..............
}
}
You can also give the connection parameters for occasions when you want to connect to different databases for some reason:
<?php
function db_connect($hostname, $database, $username, $password)
{
$db = "mysql:host=$hostname;dbname=$database;charset=utf8mb4";
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC);
return new PDO($db, $username, $password, $options);
}
function get_data()
{
$db = db_connect('localhost', 'database', 'username', 'password');
///......
} Or you can compress it:
<?php
function db_connect()
{
$db = "mysql:host=localhost;dbname=database;charset=utf8mb4";
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC);
return new PDO($db, 'username', 'password', $options);
} Just like that there is no more global $db;.
A drained and empty Kennington reservoir images from a drone in early July 2024. The…
Merrimu Reservoir from drone. Click images to view larger.
Using FTP and PHP to get an array of file details such as size and…
Creating and using Laravel form requests to create cleaner code, separation and reusability for your…
Improving the default Laravel login and register views in such a simple manner but making…
Laravel validation for checking if a field value exists in the database. The validation rule…