Database Operation Handling in PHP

Sayed Ahmed
Nov 29 · 1 min read
Not the best approach. Just one approach. At least to help with thinking. to start with.

< ?php

//you can keep database parameters in a file [text file or xml file].

/*
Create two users one with only read permission, another with read-write permission.
Use read user related connection in read only operations.
read-write user related database connection should be used only when writing is associated
*/

//database user with read only permission
$roUser = "";
$roPassword = "";

//database user with read-write permission
$rwUser = "";
$rwPassword = "";

//database and the host $host = "localhost";
$database = "your_database";

?>

< ?php

//read only handle to database
$dbhReadOnly = null;

//read-write handle to database
$dbhReadWrite = null;

//read-write connection creation
function getDbhReadWrite(){

global $rwUser, $rwPassword, $host, $database;
//connect to db with user that has read-write permission to the database
$dbhReadWrite = mysqli_connect( "$host", "$rwUser", "$rwPassword", "$database");
//var_dump($dbhReadWrite);
if (!($dbhReadWrite))
return null;
return $dbhReadWrite;

}

//read-only connection creation
function getDbhReadOnly(){
global $roUser, $roPassword, $host, $database;

//connect to the database with a user that has only read permission to the database

$dbhReadOnly = mysqli_connect( "$host", "$roUser", "$roPassword", "$database");

if (!($dbhReadOnly))
return null;
return $dbhReadOnly;
}

//read-only connection - can be used from other php files
$dbhReadWrite = getDbhReadWrite();

//read-write connection-
$dbhReadOnly = getDbhReadOnly();

?>
Sayed Ahmed

Written by

Software Engineer, Data Scientist, Machine Learning Engineer.