I have 2 form with array
<form action="addschedule.php" method="post">
<?php
$n = 0;
$c = 0;
echo "<Select name='jam[]'>";
do{
if($c>10){$n="";}
echo "<option>".$n.$c.":00</option>";
echo "<option>".$n.$c.":30</option>";
$c++;
}while($c<24);
?>
<input type="text" name="nampro[]"></td>
<input type="submit" id="submit" class="btn btn-success" value="submit">
</form>
<input class="btn btn-primary" id="addrow" value="Add Row">
then it will looks like this
This is addschedule.php
<?php
include_once("connect.php");
if(!empty($_POST['jam'])){
foreach($_POST['jam'] as $jmt){
echo $jmt."<br>";
echo $_POST['nampro'];
}
}
?>
i want to insert that 'jam' and 'nampro' into mysql
$result=$mysqli->query('INSERT INTO SCHEDULE VALUES ('$jam','$nampro');
but how can i get 'nampro' Or anyone has a better way to do this ? Im new in PHP so can anyone help?
As i can see both array is of same length, so you can do following:
$jam = $_POST['jam'];
$namePro = $_POST['nampro'];
$sql = array();
foreach( $jam as $key=>$val ) {
$sql[] = '("'.$val.'", '.$namePro[$key].')';
}
$result = $mysqli->query('INSERT INTO SCHEDULE VALUES '.implode(',', $sql));
Explanation:
$jam = ['test','google','facebook','yahoo'];
$namePro = [123,112,110,100];
$sql = array();
foreach( $jam as $key=>$val ) {
$sql[] = '("'.$val.'", '.$namePro[$key].')';
}
echo('INSERT INTO SCHEDULE VALUES '.implode(',', $sql));
will give you output:
INSERT INTO SCHEDULE VALUES ("test", 123),("google", 112),("facebook", 110),("yahoo", 100)
try this code
<?php
include_once("connect.php");
if(!empty($_POST['jam'])){
$namproPost = $_POST['nampro'];
foreach($_POST['jam'] as $key=>$jmt){
// echo $jmt."<br>";
$nampro = $namproPost[$key];
$result=$mysqli->query('INSERT INTO SCHEDULE VALUES ($jmt,$nampro)');
}
}
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With