The problem is found in this line:
$sql = "INSERT INTO observacion (id,motivo)
VALUES('".mysqli_real_escape_string($conn, $_POST['id'][$i])."','".mysqli_real_escape_string($conn, $_POST["name"][$i])."')";
Specifically in $_POST['id'][$i]
, the id
from the form is not being sent as an array but as a variable.
<input type="text" name="id" value="01">
The way to solve it is simple
Well we call $_POST['id']
as is without the [$i]
since it seems to be the same id
for all comments.
Or we indicate that it is a Array
in the form with the square brackets [ ]
.
<input type="text" name="id[]" value="01">
For this specific case, it would be advisable to use prepared sentences since they allow us to execute the same sentence by iterating only the values, quickly. Apart from simplifying the code and facilitating the prevention of SQL injection.
Example of code with prepared sentences, I also corrected some errors that I saw.
form
<div class="container">
<!-- Este input deberia estar dentro del form -->
<!-- <input type="text" name="id" value="01"> -->
<div class="form-group">
<!-- En el form falta el action y el method -->
<form name="add_name" id="add_name" action="#" method="POST">
<input type="text" name="id" value="01">
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td><input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" /></td>
<td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
</tr>
</table>
<!-- el type deberia ser submit en el boton de envio -->
<input type="submit" name="submit" id="submit" class="btn btn-info" value="Submit" />
</div>
</form>
</div>
</div>
PHP
// se asume conexion en $conn interfaz MySQLi
include 'include/conexion.php';
// Comprobamos si se envio el form
if ( isset($_POST['submit']) AND isset($_POST['id']) )
{
// comprobamos que haya almenos un elemento name
if(count($_POST["name"]) > 0)
{
// creamos la consulta
$sql = "INSERT INTO observacion (id,motivo) VALUES( ?, ? );";
// preparamos la consulta
$stmt = $conn->prepare($sql);
// asignamos id
$id = $_POST['id'];
// recorremos $_POST['name']
foreach ($_POST['name'] as $motivo)
{
//comprobamos que se escribio algo
if(trim($motivo) != '')
{
// si se escribio ejecutamos la co
$stmt->bind_param('ss', $id, $motivo);
$stmt->execute();
}
}
?>
<div class="text-center">
<div class="alert alert-success" role="alert">
<strong>Observacion Ingresada!</strong>
</div>
</div>
<?php
}
else
{
echo "Please Enter Name";
}
}
I leave the code in a file.php to test it, just configure the data of the database, it assumes a table called 'observation' with at least the columns'id' and'motivo':
Full_example.php
<!DOCTYPE html>
<html>
<head>
<title>Form</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
});
</script>
</head>
<body>
<div class="container">
<!-- Este input deberia estar dentro del form -->
<!-- <input type="text" name="id" value="01"> -->
<div class="form-group">
<!-- En el form falta el action y el method -->
<form name="add_name" id="add_name" action="#" method="POST">
<input type="text" name="id" value="01">
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td><input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" /></td>
<td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
</tr>
</table>
<!-- el type deberia ser submit en el boton de envio -->
<input type="submit" name="submit" id="submit" class="btn btn-info" value="Submit" />
</div>
</form>
</div>
</div>
<?php
$conn = new mysqli('localhost', 'usuario', 'contraseña', 'base_datos') or die("Error con la base de datos.");
/* Comprueba la conexión */
if ($conn->connect_errno) {
printf("Connect failed: %s\n", $conn->connect_error);
exit;
}
// se asume conexion en $conn interfaz MySQLi
//include 'include/conexion.php';
// Comprobamos si se envio el form
if ( isset($_POST['submit']) AND isset($_POST['id']) )
{
// comprobamos que haya almenos un elemento name
if(count($_POST["name"]) > 0)
{
// creamos la consulta
$sql = "INSERT INTO observacion (id, motivo) VALUES( ?, ? );";
// preparamos la consulta
$stmt = $conn->prepare($sql);
// asignamos id
$id = $_POST['id'];
// recorremos $_POST['name']
foreach ($_POST['name'] as $motivo)
{
//comprobamos que se escribio algo
if(trim($motivo) != '')
{
// si se escribio ejecutamos la co
$stmt->bind_param('ss', $id, $motivo);
$stmt->execute();
}
}
?>
<div class="text-center">
<div class="alert alert-success" role="alert">
<strong>Observacion Ingresada!</strong>
</div>
</div>
<?php
}
else
{
echo "Please Enter Name";
}
}
?>
</body>
</html>