Hello Everyone and welcome back to another tutorial of Tutoid and today i will show you how you can enter data into database using prepared statements which is secure and efficient method of executing SQL queries. In the previous post i gave introduction about Prepared StatementsĀ and how it works, you can refer to article for more information. Click Here to read the post.

So first we start with creating a connection to our database using our username and password specified.

$conn = mysqli_connect('localhost','root','password','database'); // localhost is server address,root username

Now we prepare our database for the query we want to execute to our database. Here ‘?’ are the parameters and later we will define them.

$query = "insert into users (username,email,password) values (?,?,?)";
$statement = $conn->prepare($query);

So now it’s time for setting or defining the variables.

$username = 'abcdef';
$password = md5('abcdef');
$email = 'abcdef@gmail.com';

Now we pass on the values for the parameters so that our database can execute it easily.

$statement->bind_param('sss',$username,$email,$password);
if($statement->execute()){
echo 'Query Executed!';
}
else {
echo 'Failed!';
};
$statement->close();
$conn->close();

If you want to enter more data into database, you can simply define same variables with different values before closing the statement and connection.

So Finally the whole script is ready now, it looks something like this.

<?php
$conn = mysqli_connect('localhost','root','','test');
$query = "insert into users (username,email,password) values (?,?,?)";
$statement = $conn->prepare($query);
$username = 'abcdef';
$password = md5('abcdef');
$email = 'abcdef@gmail.com';
$statement->bind_param('sss',$username,$email,$password);
if($statement->execute()){
echo 'Query Executed!';
}
else {
echo 'Failed ';
};
$statement->close();
$conn->close();
?>

So now you are ready to enter data into database using prepared statements securely and efficiently.

Advertisements