$name=$_POST['name'];
$class=$_POST['class'];
$mark=$_POST['mark'];
$gender=$_POST['gender'];
We can set the variables with value for our example.
$name='Alex R';
$class='Five';
$mark=70;
$gender='Female';
is our datbase connection object declared inside config.php file. We will directly go to query part.
require "config.php"; // Database Connection, $dbo is available here
$query="INSERT INTO student SET name=:name,
class=:class, mark=:mark, gender=:gender";
$step=$dbo->prepare();
$step->bindParam(':name',$name,PDO::PARAM_STR, 15);
$step->bindParam(':class',$class,PDO::PARAM_STR, 15);
$step->bindParam(':mark',$mark,PDO::PARAM_INT,5);
$step->bindParam(':gender',$gender,PDO::PARAM_STR,10);
if($step->execute()){
$mem_id=$dbo->lastInsertId();
echo " Thanks .. Your Membership id = $mem_id ";
}
else{
echo " Not able to add data please contact Admin ";
}
This code connects to a database using config.php and inserts a record into the student table. It uses prepared statements to securely bind user-provided values (name, class, mark, and gender) to the query. After executing the statement, it retrieves the lastInsertId() to get the ID of the newly inserted record. If the query executes successfully, it displays the new membership ID. If it fails, an error message is shown.
This example demonstrates how to use named parameters for inserting user data securely into a database.
try {
$sql = "INSERT INTO student (name, class, mark,gender)
VALUES (:name, :class, :mark,:gender)";
$stmt = $dbo->prepare($sql);
$stmt->execute(['name'=>'Alice','class' =>'Five','mark' => 95,'gender'=>'Female']);
$mem_id=$dbo->lastInsertId();
echo " Thanks .. Your Membership id = $mem_id ";
}
catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
Output:
Thanks .. Your Membership id = 37
try{
$students = [
['name' => 'Bob', 'class' => 'Six', 'mark' => 89,'gender'=>'Male'],
['name' =>'Charlie','class' =>'Seven','mark' => 76,'gender'=>'Female']
];
$sql = "INSERT INTO student (name, class, mark, gender)
VALUES (:name, :class, :mark,:gender)";
$stmt = $dbo->prepare($sql);
foreach ($students as $student) {
$stmt->execute($student);
echo "<br> Student ID : ". $dbo->lastInsertId();
}
}
catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
Output
Student ID : 40
Student ID : 41
try {
$dbo->beginTransaction(); // Start the transaction
// First Insert
$query1 = "INSERT INTO student (name, class, mark, gender)
VALUES ('John Doe', 'Six', 85, 'Male')";
$dbo->exec($query1);
// Second Insert
$query2 = "INSERT INTO student (name, class, mark, gender)
VALUES ('Jane Doe', 'Seven', 90, 'Female')";
$dbo->exec($query2);
$dbo->commit(); // Commit the transaction if both queries succeed
echo "Data inserted successfully!";
} catch (Exception $e) {
$dbo->rollBack(); // Roll back the transaction on error
echo "Transaction failed: " . $e->getMessage();
}
$my_conn
, while for MySQL, it's $dbo
. This guide demonstrates the process of submitting and storing data securely through prepared statements.This example shows how to handle errors using exceptions in PDO during the insert process.
try {
$stmt->execute($data);
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
Output:
Error: SQLSTATE[23000]: Integrity constraint violation
To get more meaning full information from the database we have to use errorinfo() function. We will modify the part of the above code like this.
if($step->execute()){
$mem_id=$dbo->lastInsertId();
echo " Thanks .. Your Membership id = $mem_id ";
}
else{
echo " Not able to add data please contact Admin ";
print_r($step->errorInfo());
}
require "config.php"; // Database Connection, is available here
try {
if ($mark > 100) {
throw new Exception("Mark cannot be greater than 100. Please check the input.");
}
$query = "INSERT INTO student SET name=:name,
class=:class, mark=:mark, gender=:gender";
$step = $dbo->prepare($query);
$step->bindParam(':name', $name, PDO::PARAM_STR, 15);
$step->bindParam(':class', $class, PDO::PARAM_STR, 15);
$step->bindParam(':mark', $mark, PDO::PARAM_INT, 5);
$step->bindParam(':gender', $gender, PDO::PARAM_STR, 10);
if ($step->execute()) {
$mem_id = $dbo->lastInsertId();
echo "Thanks .. Your Membership id = $mem_id";
} else {
echo "Not able to add data, please contact Admin";
}
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
Storing error message in a string and passing to front end
$str='';
$dbo->setAttribute(PDO::ATTR_EMULATE_PREPARES,false);
$a=$step->errorInfo();
while (list ($key, $val) = each ($a) ) {
$str .= "<br>$key -> $val <br>";
}
$msg .= " Not able to add data please contact Admin $str";
$dt=date("Y-m-d");// Today's date
$step->bindParam(':dt',$dt,PDO::PARAM_STR,10);
$date = new DateTime($dt);
$dt=$date->format('Y-m-d');
Here $dt is the variable storing date field value.
$dt=null; // make it null
$step->bindParam(':dt',$dt,PDO::PARAM_STR,10);
If you are receiving date field as blank from a form then use this PHP script.
if(strlen($dt) >2){
$date = new DateTime($dt_approved);
$dt=$date->format('Y-m-d');
}else{
$dt=null;
}
$step=$dbo->prepare("insert into table_name(dt) values(:dt)");
$step->execute();
Download Zip file to test your PHP PDO script