There are lots of examples for using PDO functions for handling MySQL queries in PHP. PDO with simple PHP functions makes the developer more versatile to develop web applications or websites.

In this topic, we are going to see some useful PHP functions that help to make your programming, even more, better than ever.

Function for Inserting data into a database using functions.

Using simple MySQL and PHP

/*******Function to Insert data *******/

function Insertdata($table,$field,$data){
global $con;
$fields = implode('`, `', $field);
$values = implode("', '", $data);
$sql = "INSERT INTO `{$table}` (`{$fields}`) VALUES ('{$values}')";
// echo $sql;
$result = query($sql);
confirm($result);
return true;
}

/******Function to Insert data using PDO*****/

function Insertdata($table,$field,$exec){
global $con;
$flag = 0;
$query = "INSERT INTO ". $table . "(";
foreach($field as $rows){
if($flag==0){
$query= $query . $rows;
$flag=1;
}
else{
$query= $query . "," . $rows;
}
}
$flag = 0;
$query = $query . ") VALUES (";
foreach($field as $rows){
if($flag==0){
$query= $query . "?";
$flag=1;
}
else{
$query= $query . ", ?";
}
}
$query = $query . ")";
$stmt = $con->prepare($query);
$i=1;
foreach ($exec as $values)
{
$stmt->bindValue($i,$values,PDO::PARAM_STR);
$i=$i+1;
}
if($stmt->execute()){
}
return true;
}

The below functions are necessary to be added to make the previous functions run properly.

/*****For the Simple SQL Functions*****/

$con = mysqli_connect('localhost','root','password','database');
//This functions handles the query executions easily
function query($query){
global $con;
return mysqli_query($con,$query);
}

//This function verifies that the query has ran successfully or not

function confirm($result){
global $con;
if(!$result){
die ("Query Failed".mysqli_error($con));
}
}

/*****For the SQL Functions using PDO*****/

$con = new PDO('mysql:host=localhost;dbname=dbname','root','password');

Comment below about the functions you want to make it simple like this or to know how this functions works in PHP