PHP CRUD | How to insert data into database

Welcome readers! We are back with another interesting article. Nosotros will hash out how to insert data in the database which is the start part of PHP CRUD. In Grime, C stands for "create" (Insert Operation). This article'southward main focus is to explain Create or Insert function of the Grime in item. Showtime of all, we will create a new "book" table in our library database. And so, we will create an HTML grade to have input from the user. We will also apply server-side validation on the form. Finally, we will submit the class to a pure PHP page to execute the insert query and perform the insert operation.

Creating a "book" table in the database:

  • Open up "localhost/phpmyadmin" in whatever browser to create your table.
  • Create a new table "book" in our library database that we created in our database connectivity article.
  • Click on "new" under the database name "library".

PHP CRUD | How to insert data into database

  •  Name the table as "book" and add "v" columns.
  • Proper name the commencement column every bit "id" and set its length to twenty. Likewise, check the machine-increment checkbox. This column will act equally the master key of the table.
  • Name the second column as "user_id" and set its length to twenty.  It will be the strange primal of the user table. Nosotros need the strange primal to keep the tape of the user uploading the book.

PHP CRUD | How to insert data into database

  • Name the rest of the columns every bit title, author, clarification, and date. Set their lengths every bit 200, 200, 1500, and 200.
  • Click on the Salvage button and your "volume" table is created now. But it does not have any information yet.

PHP CRUD | How to insert data into database

Note: All the column names and the lengths of the columns are adjusted according to our project requirements.

At present let'due south create the HTML form to have input from the user.

Creating HTML grade:

  • Create an "addbook.php" file in your project. This file will mainly contain our HTML code.
  • Create one more file "addbook.inc.php" inside the includes folder. I prefer to keep all pure PHP files in a split binder and I commonly proper name the folder as "includes".
  • At the very start, write PHP code to avoid unauthorized access to the folio. The user must be logged in to access this folio.
                      <?php                      
session_start();
if(! isset($_SESSION['id']) && ! isset($_SESSION['electronic mail']) ){

header("location: login.php");
}

?>

  • Include bootstrap 5 into your code to way the HTML form easily.
  • Create bootstrap navigation to show the log-out button and name to the user
  • create a bootstrap grid with a unmarried row and a single column.
  • In the column, create your form to accept input from the user.
  • Create two text fields for the volume title and author name. As well, create one text expanse for the description of the volume.
  • Create a submit button to submit the form to the "addbook.inc.php" file.
  • As well, set the method attribute to POST and gear up the action of the form to "includes/addbook.inc.php".
  • Add some manner to apply blue and white slope color to the navbar and HTML form container.
                      <                      way                      type                      =                      "text/css"                      >                      
.navbar{
background : -webkit-linear-gradient(to right , #5bc0de, #fff);
background : linear-gradient(to right , #5bc0de, #fff);
}
.col-6{
margin-top : v%;
background : -webkit-linear-slope(to right , #5bc0de, #fff);
background : linear-slope(to correct , #5bc0de, #fff);
}

</ style >

Now see the complete working code of all the above-stated steps at once.

                    <?php                    
session_start();
if(! isset($_SESSION['id']) && ! isset($_SESSION['email']) ){

header("location: login.php");
}
?>

<!doctype html>
<html lang= "en" >
<caput>
<!-- Required meta tags -->
<meta charset= "utf-8" >
<meta name= "viewport" content= "width=device-width, initial-scale=ane" >

<!-- Bootstrap CSS -->
<link href= "https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel= "stylesheet" integrity= "sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin= "anonymous" >

<title>Add together Book</title>
<style type= "text/css" >
.navbar{
groundwork : -webkit-linear-gradient(to right , #5bc0de, #fff);
background : linear-gradient(to correct , #5bc0de, #fff);
}
.col-6{
margin-peak : 5%;
background : -webkit-linear-gradient(to right , #5bc0de, #fff);
background : linear-gradient(to right , #5bc0de, #fff);
}

</style>
</head>
<trunk>
<!--Starts Here NavBar-->
<nav course= "navbar navbar-expand-lg navbar-light" >
<div class= "container-fluid" >
<a class= "navbar-make" href= "#" ><h3>My Library</h3></a>
<button class= "navbar-toggler" blazon= "button" data-bs-toggle= "collapse" data-bs-target= "#navbarNavAltMarkup" aria-controls= "navbarNavAltMarkup" aria-expanded= "fake" aria-label= "Toggle navigation" >
<span class= "navbar-toggler-icon" ></bridge>
</button>
<div course= "plummet navbar-collapse" id= "navbarNavAltMarkup" >
<div class= "navbar-nav ms-auto mb-2 mb-lg-0 " >
<a course= "nav-link" href= "#" > <?php repeat "Hello! " . $_SESSION['proper name'] ?> </a>
<a course= "nav-link" href= "includes/logout.inc.php" >Log out</a>
</div>
</div>
</div>
</nav>

<!--Addbook form container-->
<div form= "container-fluid " >
<div class= "row justify-content-center" >
<div class= "col-6 text-center mb-5 py-5 px-5" >
<h1 grade= "text-center mb-v text-nighttime" >Add books and Spread Knowledge</h1>
<course method= "POST" action= "includes/addbook.inc.php" >
<div class= "form-grouping my-3" >

<input type= "text" form= "form-control" placeholder= "Enter Title" proper noun= "title" >
</div>
<div form= "form-group my-iii" >

<input type= "text" class= "form-control" placeholder= "Enter Author" name= "Author" >
</div>
<div form= "form-group my-3" >

<textarea class= "form-control" rows= "5" name= "desc"
placeholder= "Enter Description" style= "resize: none;" ></textarea>
</div>
<push button blazon= "submit" name= "submit" class= "btn my-3 fs-five px-4"
manner= "background:#068a9c" >Submit</button>
<a href= "#" form= "btn btn-danger text-night my-3 fs-5 px-four" >Go Dorsum</a>
</form>

<!--Real Errors will be printed in the last paart of article-->

<p class= 'alarm alarm-danger' >

                    
                                                                                              <!--temporary warning -->                    

Warning! Description is too short.Min 20 words required. </p> </div> </div> </div> <!--Starts Here Footer--> <footer form= " text-center text-dark edge-elevation" > <!-- Copyright --> <div grade= "text-center p-3" > © 2020 Copyright: <a href= "world wide web.Programmopedia.com" > programmopedia.com </a> </div> <!-- Copyright --> </footer> <script src= "https://cdn.jsdelivr.net/npm/bootstrap@five.0.2/dist/js/bootstrap.bundle.min.js" integrity= "sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin= "anonymous" ></script> </body> </html>

Now run across the effect of the "addbook.php" file.

PHP CRUD | How to insert data into database

Applying server-side validation on the form:

  • Open up the "addbook.inc.php" file to write PHP code. Read our server-side validation commodity to learn it in item.
  • Using the if statement and PHP isset() role, bank check whether the form is submitted properly.
  • Save the data retrieved in the $_POST associative array into PHP variables.
  • Apply validation on the course data to bank check if there is an empty field using the PHP empty() office. Use PHP header() function to generate error through $_GET variable if any of the fields are empty.
  • Utilize another validation on the description field. Don't allow the user to submit the form if the description is less than twenty words. Use PHP str_word_count() function to employ this validation.

Now we are done with the server-side validation. A working code case is given below.

                    <?php                    

session_start();
if(isset($_POST['submit'])){

$title = mysqli_real_escape_string($conn, $_POST["title"]);
$Writer = mysqli_real_escape_string($conn, $_POST["Writer"]);
$desc = mysqli_real_escape_string($conn, $_POST["desc"]);
$date = mysqli_real_escape_string($conn, appointment("l jS of F Y h:i:south A"));
$user_id = $_SESSION["id"];

//Server side validation//
if(empty($title) && empty($Author) && empty($desc) ){
header("location: ../addbook.php?fault=AllInputsEmpty");
go out();
}
if(empty($championship)){
header("location: ../addbook.php?error=EmptyTitle");
exit();
}
if(empty($Author)){
header("location: ../addbook.php?error=EmptyAuthor");
exit();
}
if(empty($desc)){
header("location: ../addbook.php?error=EmptyDesc");
exit();
}

if(str_word_count($desc)<twenty){
header("location: ../addbook.php?error=InvalidDesc");
exit();
}
?>

Inserting data into books table:

  • Include the database connectivity file "db.inc.php". Read our database connectivity commodity to learn about this file.
  • Write SQL insert query to insert data into database table.
  • Execute the query using PHP mysqli_query() function which takes $conn(connexion variable) and $query (SQL query) every bit parameters.
  • Check if the query is successfully executed using the if statement.
  • If not executed, utilize the die() function to print an mistake message. Yous can also use the myslqi_error() function to print the description of the fault.
  • If the query is successfully executed, use the header() part to redirect the user to the "addbook.php" page.
                      <?php                    
                      crave                                            "db.inc.php"                      ;                    
                                              $query                      =                      "INSERT INTO `volume`(`user_id`, `championship`, `Author`,`description`,`date`)                                            
VALUES ( $user_id ,' $title ',' $Author ',' $desc ',' $appointment ')";

if(mysqli_query($conn, $query)){

header("location: ../addbook.php?error=success");
}else{

die("error while executing the query" . mysqli_error($conn));

}
}else{
dice("fault while submiting the grade");
}

mysqli_close($conn);

?>

We have successfully inserted information into the "volume" tabular array. Let's meet the complete working lawmaking beneath.

                      <?php                      
require "db.inc.php";
session_start();
if(isset($_POST['submit'])){

$title = mysqli_real_escape_string($conn, $_POST["title"]);
$Author = mysqli_real_escape_string($conn, $_POST["Author"]);
$desc = mysqli_real_escape_string($conn, $_POST["desc"]);
$appointment = mysqli_real_escape_string($conn, date("50 jS of F Y h:i:south A"));
$user_id = $_SESSION["id"];

//Server side validation//
if(empty($title) && empty($Writer) && empty($desc) ){
header("location: ../addbook.php?fault=AllInputsEmpty");
exit();
}
if(empty($title)){
header("location: ../addbook.php?error=EmptyTitle");
exit();
}
if(empty($Author)){
header("location: ../addbook.php?mistake=EmptyAuthor");
exit();
}
if(empty($desc)){
header("location: ../addbook.php?error=EmptyDesc");
exit();
}

if(str_word_count($desc)<20){
header("location: ../addbook.php?error=InvalidDesc");
exit();
}

//Server side validation ends here
//executing query to insert data

$query = "INSERT INTO `book`(`user_id`, `championship`, `Author`,`clarification`,`engagement`)
VALUES ( $user_id ,' $title ',' $Writer ',' $desc ',' $engagement ')";

if(mysqli_query($conn, $query)){

header("location: ../addbook.php?error=success");
}else{

die("fault while executing the query" . mysqli_error($conn));

}
}else{
die("error while submiting the form");
}

mysqli_close($conn);

?>

Now Permit's encounter the result of the "addbook.inc.php" file in the below-shared screenshot.

PHP CRUD | How to insert data into database

Here is the result. The data is inserted into the database successfully. Now let'due south print proper alerts on "addbook.php".

Press alerts to users:

  • Open up the "addbook.php" file again to bear witness proper alarm messages to users.
  • Remove the temporary alert message.
  • Write PHP script nether the form tag to display alerts to users.
  • Check if the $_GET["error"] variable is set using if statement and PHP isset part.
  • At present check for all the errors and impress proper alert letters using nested if statement.

Check out the PHP code to print alerts letters to users.

                      <?php                      
if(isset($_GET["fault"])){

if($_GET["error"]== "AllInputsEmpty"){

echo "
<p class='alarm alert-danger'>
Alarm! All input Fields are Empty.
</p>
";
}

if($_GET["mistake"]== "EmptyTitle"){

echo "
<p form='alarm warning-danger'>
Warning! Championship tin not be empty.
</p>
";
}

if($_GET["error"]== "EmptyAuthor"){

echo "
<p class='alert alert-danger'>
Alert! Author name can not be empty.
</p>
";
}

if($_GET["error"]== "EmptyDesc"){

echo "
<p form='warning alert-danger'>
Warning! Description can non exist empty.
</p>
";
}

if($_GET["error"]== "InvalidDesc"){

echo "
<p class='alert warning-danger'>
Warning! Description is as well brusk.Min 20 words required.
</p>
";
}

                      }
?>

 Finally, we have successfully inserted information into the database, applied proper validations, and also printed proper alert messages to users. Now permit's end the article here and see you in the next one with more useful information. Thanks for reading and supporting us.