Sandeep Kumar Sandeep Kumar - 1 month ago 14
MySQL Question

Insert data of multiple form fields by foreach loop

I have four fields. Two name fields and two email fields. I have to insert all fields data by foreach loop but when I insert data through foreach loop, a blank entry also inserts in database.

sample code

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form method="post">
Name : <input type="text" name="name[]"><br>
Email : <input type="text" name="email[]"><br>
Name : <input type="text" name="name[]"><br>
Email : <input type="text" name="email[]"><br>
<input type="submit" name="submit">
</form>
</body>
</html>

[![<?php
if(isset($_POST['submit']))
{
$conn = mysqli_connect("localhost", "root", "", "practice");
$i=0;

foreach($_POST as $val)
{
$name=$_POST['name'][$i];
$email=$_POST['email'][$i];

$sql = "insert into interview (Name, Email) values ('$name', '$email')";
$result = mysqli_query($conn, $sql);
$i++;

}

}
?>


Can anybody help me ?

This is my database table screen shot.

Answer

Since name and email are indexed the same, just loop one and reference the other by key:

foreach($_POST['name'] as $key => $val) {
    $name  = $val;
    $email = $_POST['email'][$key];

    $sql = "insert into interview (Name, Email) values ('$name', '$email')";
    $result = mysqli_query($conn, $sql);
}

Or you could do inputs like this to get arrays more like database rows:

Name  : <input type="text" name="data[0][name]"><br>
Email : <input type="text" name="data[0][email]"><br>

Then loop it easily:

foreach($_POST['data'] as $val) {
    $name  = $val['name'];
    $email = $val['email'];
}
Comments