Insert data into database in php mysql
In this post, you will be learning about how to insert data into database in php mysql, so, lets create a table named student to insert data in mysql using php as given in STEP 1.
We are using Bootstrap v4 to design the user interface like forms and table.
So, Let's get started: (To insert data into database in php mysql).
Step 1: Create a database phpcrud and in that create a table named student :
CREATE TABLE student (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
fname VARCHAR(30) NOT NULL,
lname VARCHAR(30) NOT NULL,
contact VARCHAR(50) NOT NULL,
)
Step 2: Create a file named insertdata.php and we will use bootstrap to design the form and store data through that html form, where code given below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<title>Insert Data into Database in PHP</title>
</head>
<body>
<div class="container">
<div class="jumbotron">
<div class="row">
<div class="col-md-12">
<h2> PHP - CRUD : ADD Data </h2>
<hr>
<form action="" method="post">
<div class="form-group">
<label for=""> First Name </label>
<input type="text" name="fname" class="form-control" placeholder="Enter First Name" required>
</div>
<div class="form-group">
<label for=""> Last Name </label>
<input type="text" name="lname" class="form-control" placeholder="Enter Last Name" required>
</div>
<div class="form-group">
<label for=""> Contact </label>
<input type="text" name="contact" class="form-control" placeholder="Enter Contact" required>
</div>
<button type="submit" name="insert" class="btn btn-primary"> Save Data </button>
<a href="index.php" class="btn btn-danger"> BACK </a>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
Now, we have successfully created the HTML FORM using Bootstrap to insert data in STEP 2, so guys now lets write the code to insert data into database in php mysql in the same file just you created. (insertdata.php).
Paste the below given code at the TOP of the FILE named (insertdata.php)
<?php
$connection = mysqli_connect("localhost","root","");
$db = mysqli_select_db($connection, 'phpcrud');
if(isset($_POST['insert']))
{
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$contact = $_POST['contact'];
$query = "INSERT INTO student(`fname`,`lname`,`contact`) VALUES ('$fname','$lname','$contact')";
$query_run = mysqli_query($connection, $query);
if($query_run)
{
echo '<script> alert("Data Saved"); </script>';
}
else
{
echo '<script> alert("Data Not Saved"); </script>';
}
}
?>
Thanks for reading...