All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

How To Insert Multiple Array Values Into Database PHP

Last Updated : Mar 11, 2024

How To Insert Multiple Array Values Into Database PHP

In this article we will show you the solution of how to insert multiple array values into database PHP, an array value can be stored in MySQL and PHP by following these steps. Multiple arrays can be inserted into a MySQL database using PHP.

The PHP MySQL code converts array values row-wise to columns and inserts many arrays column-wise

The click() function in jquery will create multiple form rows by clicking the button multiple times; on the other hand, the remove() function will remove the desired row in order to insert multiple form data.

The length of a row will be calculated when we click on the add new row button for the first time using the class attribute of the field SL No.

In the next step, we will increase the number of rows by adding 1 with parseInt(1) and storing the result in a variable called i.

Step By Step Guide On How To Insert Multiple Array Values Into Database PHP :-

<?php
//session_start();
include('connect.php');
if(isset($_POST['submit'])){
for($i=0;$i<count($_POST['slno']);$i++){
                  $student_name = $_POST['student_name'][$i];
                  $phone_no = $_POST['phone_no'][$i];
                  $age = $_POST['age'][$i];
                  $date_of_birth = $_POST['date_of_birth'][$i];
                  if($student_name!=='' && $phone_no!=='' && $age!=='' && $date_of_birth!==''){
      $sql="INSERT INTO student(student_name,phone_no,age,date_of_birth)VALUES('$student_name','$phone_no','$age','$date_of_birth')";
                              $stmt=$con->prepare($sql);
                              $stmt->execute();
                      //echo '<div class="alert alert-success" role="alert">Submitted Successfully</div>';
                  }
                  else{
                              echo '<div class="alert alert-danger" role="alert">Error Submitting in Data</div>';
                  }
      }
      echo "<script type='text/javascript'>";
                  echo "alert('Submitted successfully')";
                  echo "</script>";
}
?>
<html>
<head>
<title>ajax example</title>
<link rel="stylesheet" href="bootstrap.css" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="bootstrap-theme.css" crossorigin="anonymous">
<style>
.container{
      width:80%;
      height:30%;
      padding:20px;
}
</style>
</head>
<body>
<div class="container">
<h3 align="center"><u>Inserting Multiple Rows in PHP</u></h3>
<br/><br/><br/>
      <form class="form-horizontal" action="#" method="post">
      <div class="row">
                  <div class="col-sm-1">
            <label for="Age">Sl No:</label>
            <input type="text" class="form-control sl" name="slno[]" id="slno" value="1" readonly="">
          </div>
          <div class="col-sm-3">
            <label for="Student Name">Student Name:</label>
            <input type="text" class="form-control" name="student_name[]" id="st_name" placeholder="Enter Student Name">
          </div>
          <div class="col-sm-3">
          <label for="Phone">Phone No*:</label>
            <input type="text" class="form-control" name="phone_no[]" id="pn" placeholder="Enter Phone No">
          </div>
          <div class="col-sm-1">
            <label for="Age">Age:</label>
            <input type="text" class="form-control" id="age" name="age[]" placeholder="Enter Age">
          </div>
                  <div class="col-sm-3">
          <label for="DateofBirth">Date of Birth:</label>
              <input type="date" id="dob" name="date_of_birth[]" class="form-control"/>
          </div>
                  </div><br/>
                  <div id="next"></div>
                  <br/>
      <button type="button" name="addrow" id="addrow" class="btn btn-success pull-right">Add New Row</button>
      <br/><br/>
      <button type="submit" name="submit" class="btn btn-info pull-left">Submit</button>
      </form>
</div>
<script src="jquery-3.2.1.min.js"></script>
<script src="bootstrap.min.js"></script>
<script>
$('#addrow').click(function(){
                  var length = $('.sl').length;
                  var i = parseInt(length)+parseInt(1);
                  var newrow = $('#next').append('<div class="row"><div class="col-sm-1"><label for="Age">Sl No:</label><input type="text" class="form-control sl" name="slno[]" value="'+i+'" readonly=""></div><div class="col-sm-3"><label for="Student Name">Student Name:</label><input type="text" class="form-control" name="student_name[]" id="st_name'+i+'" placeholder="Enter Student Name"></div><div class="col-sm-3"><label for="Phone">Phone No*:</label><input type="text" class="form-control" name="phone_no[]" id="pn'+i+'" placeholder="Enter Phone No"></div><div class="col-sm-1"><label for="Age">Age:</label><input type="text" class="form-control" id="age'+i+'" name="age[]" placeholder="Enter Age"></div><div class="col-sm-3"><label for="DateofBirth">Date of Birth:</label><input type="date" id="dob'+i+'" name="date_of_birth[]" class="form-control"/></div><input type="button" class="btnRemove btn-danger" value="Remove"/></div><br>');
                  });
      // Removing event here
  $('body').on('click','.btnRemove',function() {
       $(this).closest('div').remove()
  });
</script>
</body>
</html>
  1. The short tags start with "<?" and end with "?>". Short style tags are only available when they are enabled in the php.ini configuration file on servers.
  2. Then we use <ISSET> can be used to define and set a user-defined variable. The first occurrence of <ISSET> in a template declares
  3. Then we use PHP $_POST is a PHP super global variable which is used to collect form data after submitting an HTML form with method="post".
  4. Then we use The query tag is used to perform an SQL query that returns a result set. For parameterized SQL queries
  5. Then we use statement is a feature used to execute the same (or similar) SQL ... Prepare: An SQL statement template is created and sent to the database.
  6. Then we use the echo () function to output one or more strings. Note: The echo () function is not actually a function, so you are not required to use parentheses with it.
  7. In our first step, we write <HTML>, which tells the browser what HTML version we're using. Documents in HTML begin with tags.
  8. Using the <head> tag, we will explain the project's heading.
  9. <title> are open and </title> and then head closed using </head>
  10. Then we use a stylesheet.
  11. To define the body of the webpage, the <body> tag is used. This is where we write all the content on our website.
  12. Then we use <form id="form" tag for creating a form in the program.
  13. Then we use the <label> tag defines a label for several elements: <input type="checkbox">
  14. It can be added to an HTML page with a <script> tag. The script tag explains the source code.
  15. After that </script></body></html> and code should be executed after closed all tags.

Conclusion :-

The goal of the tutorial is to learn how to insert a PHP array into a MySQL table. Whenever we want to insert multiple rows of data into MySQL, we encounter this problem very often.

The process of inserting an array into MySQL can be accomplished very easily with PHP.

I hope this article on how to insert multiple array values into database PHP helps you and the steps and method mentioned above are easy to follow and implement.

Author Image About Pragati

Experienced coding content writer who enjoys breaking down complex concepts in programming languages like Java, Python, C, and C++. Over three years of experience producing interesting and relevant content for a variety of entities. Committed to providing concise and easy-to-understand articles that assist readers in easily understanding technology and industry trends in the world of coding and software development.

Follow Pragati On Linkedin 🡪