MySQL

How to insert data in MySQL using PHP PDO

In this tutorial, we are going to see how to insert data in MySQL using PHP PDO. If you are a “newbie” you should know how to connect to a MySQL database before using the code below. You cannot insert data into a table if you are not connected to it.
 

How to insert data in MySQL using PHP PDO

In the example below, we insert data into “Users” table, you can use the following script:
 

#File : process.php

<?php

$host = 'localhost';
$dbname = 'test';
$username = 'root';
$password = '';

if(isset($_POST['insert'])){

  try {
  // connect to mysql
  $pdo = new PDO("mysql:host=$host;dbname=$dbname","$username","$password");
  } catch (PDOException $exc) {
    echo $exc->getMessage();
    exit();
  }

  // Get values from submitted form
  $firstname = $_POST['firstname'];
  $lastname = $_POST['lastname'];

  // Mysql query to insert data
  $sql = "INSERT INTO `users`(`firstname`, `lastname`) VALUES (:firstname,:lastname)";
  $res = $pdo->prepare($sql);
  $exec = $res->execute(array(":firstname"=>$firstname,":lastname"=>$lastname));

  // check if the request was executed successfuly
  if($exec){
    echo 'Data inserted';
  }else{
    echo "ERROR!";
  }
}
?>

 

 

HTML from to insert data into Users table:
<!DOCTYPE html>
<html>
  <head>
    <title>Insert data into Users table</title>
  </head>
  <body>
    <form action="process.php" method="post">
      <p><input type="text" name="firstname"></p>
      <p><input type="text" name="lastname"></p>
      <p><input type="submit" name="insert" value="Insert"></p>
    </form>
  </body>
</html>
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *