Insert data into MySQL with PHP PDO


     As you might have noticed, if you try to use functions like mysql_query in PHP with version greater than 5.2. you are announced that the mysql functions are deprecated. Functions become deprecated when a new technology comes around, safer and sometimes faster. Changing the functions for running queries in this case appeared because of the developmente of the prepared statements which is much safer than the mysql functions.
     So how do we use prepared statements to insert data into MySQL database? We will see an example below in which we can understand all the means to do this properly.

Let's say we have 3 textboxes in which we input data from the keyboard, and a submit button to trigger the insertion of data into the MySQL database.

PHP code:
<?php
if (isset($_POST['submit'])) { //error handling- we want for the opearations to run once we click submit
$host       = "localhost";
$username   = "user_name";
$password   = "pass_word";
$dbname     = "form"; // will use later
$dsn        = "mysql:host=$host;dbname=$dbname"; // will use later
$options    = array(
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
              );

try { //again error handling try to run the query and catch the error
$connection = new PDO($dsn, $username, $password, $options);

    $stmt=$connection->prepare("INSERT INTO form1(name,address,phone_nr)  
       VALUES (:name,:address,:phone_nr)");  //prepare the query 

    $stmt->bindParam(':name',$name);  //bind parameters php variables
    $stmt->bindParam(':address',$address);
    $stmt->bindParam(':phone_nr',$phone_nr);

    $date = date('Y-m-d');
    $name =$_POST['name'];  //assign the value posted from the textboxes to the php variable
    $address =$_POST['address'];
    $phone_nr =$_POST['phone_nr'];

    $stmt->execute();  //submit the query for execute

}
catch(PDOException $e)
{
echo "Error: " .$e->getMessage();
}
$connection = null;
}
?>


HTML code:
<!DOCTYPE html>

<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>Data entry form</title>
  </head>

<body>
<label  for "name"> Name</label>
<input  type ="text" name="name" />

<label  for "address"> Address</label>
<input  type ="text" name="address" />

<label  for "phone_nr"> Phone number</label>
<input  type ="text" name="phone_nr" />

<input type="submit" name="submit" value="Register data">
</body>

</html>


Comments