How to use MySQL INSERT statement using PDO prepared statements




MySQL INSERT INTO Statement is used to INSERT data or records into a table. However, in this tutorial, we will not only insert data into a table but also use PDO prepared statements. This tutorial will get you going on how to use MySQL INSERT statement using PDO.

How to apply MySQL INSERT statement using PDO

MySQL PDO INSERT statement requires you to understand the order in which you have written your columns. First thing would be to connect to the database. In the Previous Article we clearly showed you how to connect to MySQL database using PDO. Be sure to check it. So go ahead and create a new file and name itconfig.inc.php, complete explanation of config.inc.php can be found here.

Config.inc.php

<?php

$severName = "localhost";
$db_name = "pdo";
$db_username = "root";
$db_password = "";

try{
	$con = new PDO("mysql:host=$severName; dbname=$db_name", $db_username, $db_password);
	$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	
	
} catch (PDOException $e){
	die($e->getMessage());
}

MySql INSERT INTO clause using PDO


require "config.inc.php";

$firstName = "Hack";
$secondName = "Smile"; 
$email = "hacksmile@gmai.com"; 

try{
	$query = $con->prepare("INSERT INTO pdo_table(firstName, secondName, email) VALUES(?, ?, ?) ");
	$query->bindParam(1, $firstName); 
	$query->bindParam(2, $secondName);
	$query->bindParam(3, $email); 
	$query->execute();
	
	echo "data inserted";
	
} catch(Exception $e){
	die($e->getMessage());
}



Explanation on how MySQL INSERT statement using PDO

MySql insert statement using PDO requires you to understand columns you are going to insert, that number matters a lot since it will make you understand how many placeholders you need. When using bindParam method, make sure columns index or numbers are well represented, for example, in our case above, secondName column is in second position in our INSERT statement, when binding it’s param, it should have 2 as the first parameter, i.e. $query->bindParam(2, $secondname).

VIDEO on How to Use MySQL INSERT statement