April 3, 2016
Insert Data From a Form Into a Database using PHP MYSQLi

Hi, friends in this tutorial I show how to insert data from a form into a database using PHP MySQL. Now we going to create an HTML form that can be used to add records to the MySQL database. If a user clicks the submit button the form data is sent to insert.php. The “insert.php” file connects to the database and gets all the values from the form with the PHP $_POST variables and mysqli_query() function executes the INSERT statement, then a record will be added into the “infom” table.
index.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<!doctype html> <html> <head> <meta charset="UTF-8"> <title>Insert Data</title> </head> <body> <form action="insert.php" method="post"> <label>Name</label><input type="text" name="name" id="name"><br/><br/> <label>Last Name</label><input type="text" name="lname" id="lname"><br/><br/> <label>Age</label><input type="text" name="age" id="age"><br/><br/> <input type="submit" value="Submit"> </body> </html> |
insert.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<?php $server = "localhost"; $user = "root"; $pass = ""; $dbname = "info"; //Creating connection for mysqli $conn = new mysqli($server, $user, $pass, $dbname); //Checking connection if($conn->connect_error){ die("Connection failed:" . $conn->connect_error); } $name = mysqli_real_escape_string($conn, $_POST['name']); $lname = mysqli_real_escape_string($conn, $_POST['lname']); $age = mysqli_real_escape_string($conn, $_POST['age']); $sql = "INSERT INTO infom (name, lname, age) VALUES ('$name', '$lname', '$age')"; if($conn->query($sql) === TRUE){ echo "Record Added Sucessfully"; } else { echo "Error" . $sql . "<br/>" . $conn->error; } $conn->close(); ?> |
Download
Mraj
Creative Designer & Developer specialist by the spirit and a loving blogger by thoughts. If you have any questions let me drop an email with the article name to the following email id: [email protected]