Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert 2 array to mysql with PHP

Tags:

arrays

php

mysql

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 enter image description here

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?

like image 826
Wingke Avatar asked Sep 22 '15 05:09

Wingke


2 Answers

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)

like image 179
Manwal Avatar answered Sep 28 '22 14:09

Manwal


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)');
        }
    }
?>
like image 32
Sandeep Nambiar Avatar answered Sep 28 '22 13:09

Sandeep Nambiar