PHP insert Data into MySQL using PDO - Web Development and Web Design Codes

Latest

Friday, April 28, 2017

PHP insert Data into MySQL using PDO

Insert Data Into Database using PHP Data Objects(PDO)

PHP insert Data into MySQL using PDO
PHP insert Data into MySQL using PDO

Hi Guys in This Lesson we will Learn How to Insert data into database Using PDO.
Very basic PDO Data Insert for Beginners.

Overviews and Setup:

Database:
Create a Database named "tutorial" and create table test under tutorial database.
Database Name: tutorial
Table Name: test
Create a Table using Follwing SQL Commands.
CREATE TABLE IF NOT EXISTS `test` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(150) NOT NULL,
  `email` varchar(150) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
Files Structure:
Create 3 files
1.index.html [this file include input form to insert data]
2.insert.php [Inserting Data into Database]
3.style.css [Design index file]
Copy below codes for your Differents Files.

Codes for index.html

<html>
<head>
<title>
Inserting Data Into MySQL Using PDO|| PDO Data Insertion Examples
</title>
<link rel="stylesheet" href="style.css" type="text/css"/>
</head>
<body>
<form method="POST" action="insert.php">
<label>Name:</label><br/>

<input type="text" name="name"/><br/>
<label>Email:</label><br/>
<input type="text" name="email"/><br/>
<input type="submit" name="submit" value="Insert"/>
</form>
</body>
</html>

Codes for insert.php

<?php
$host = "localhost";
$username = "root";
$password = "";
$dbname = "tutorial";

try {
    $conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
   $name=$_POST['name'];
   $email=$_POST['email'];
    $sql = "INSERT INTO test (name, email)
    VALUES ('$name', '$email')";
    // use exec() because no results are returned
    $conn->exec($sql);
    echo "New record Inserted successfully ||<a href=index.html>Insert a New One</a>";
    }
catch(PDOException $e)
    {
    echo $sql . "<br>" . $e->getMessage();
    }

$conn = null;
?>

Codes for style.css

input[type=text] {
    width: 40%;
    padding: 12px 20px;
    margin: 8px 0;
    box-sizing: border-box;
}
input[type=submit]{
    background-color: #4CAF50;
    border: none;
    color: white;
    padding: 16px 32px;
    text-decoration: none;
    margin: 4px 2px;
    cursor: pointer;
}
label{
 font-size:20px;
 font-weight:bold;
 color:green;
}

if you Like This Please share with Your Friends.Keep Visiting for More Codes. Thank you.

No comments:

Post a Comment

Thank You for Your Comment

Note: Only a member of this blog may post a comment.