Querying MySQL via PHP

TO Ensure we are able to dynamically call Selects inserts updates and Deletes from functions, see below on one method on how to do it via PHP to MySQL

<?php
//config.php
//echo "hit config 1 <br/>";

function OpenCon()
{
$isLocal = 0;

if($isLocal ==0)
{
$dbhost = "[IP]"; 
$dbuname = "[user name]"; 
$dbpass = "[password]"; 
$dbname = "[database]"; 
$port = "3306";
$charset = 'utf8mb4';
}else{
$dbhost = "localhost"; //need to change this to the eventual remote IP
$dbuname = "[user name]"; 
$dbpass = "[password]"; 
$dbname = "[database]"; 
$port = "3306";
$charset = 'utf8mb4';
}

$conn = mysqli_connect($dbhost, $dbuname, $dbpass,$dbname);
//echo "<br/>$dbhost, $dbuname, $dbpass,$dbname<br/>";
return $conn;

}

function CloseCon($conn)
{
//$conn -> close();
mysqli_close($conn);
}

function SelectCon($queryMe){
$conn = OpenCon();

if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

$result = mysqli_query($conn, $queryMe);// or trigger_error(mysqli_error()); 

return $result;
}

function InsertCon($insertMe){
$conn = OpenCon();
/*
echo "<br/>";
echo $insertMe;
echo "<br/>";
*/
if (!$conn) {
echo "<br/>connection failed<br/>";
die("Connection failed: " . mysqli_connect_error());
}elseif($conn){
$result = mysqli_query($conn, $insertMe);

if($result) {
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
CloseCon($conn);
return false;
}
}else{
echo "conn fail success not ran";
}
global $last_id;
$last_id = mysqli_insert_id($conn);
CloseCon($conn);

return true;
}

function UpdateCon($updateMe){
$conn = OpenCon();

if (!$conn) {
echo "<br/>connection failed<br/>";
die("Connection failed: " . mysqli_connect_error());
}elseif($conn){
$result = mysqli_query($conn, $updateMe);

if($result) {
echo "Records updated successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
CloseCon($conn);
return false;
}
}else{
echo "conn fail success not ran";
}

CloseCon($conn);

return true;
}

function DeleteCon($deleteMe){
$conn = OpenCon();

if (!$conn) {
echo "<br/>connection failed<br/>";
die("Connection failed: " . mysqli_connect_error());
}elseif($conn){
$result = mysqli_query($conn, $deleteMe);

if($result) {
echo "Records deleted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
CloseCon($conn);
return false;
}
}else{
echo "conn fail success not ran";
}

CloseCon($conn);

return true;
}
?>

Leave a Reply

Your email address will not be published. Required fields are marked *