7

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?

5
  • Where is the nampro input field in your screenshot? Commented Sep 22, 2015 at 5:46
  • it's the input type text Commented Sep 22, 2015 at 5:48
  • do you get 123 in echo $_POST['nampro']; ? Commented Sep 22, 2015 at 5:49
  • @JitendraPurohit i believe $_POST['nampro'] is an array. Commented Sep 22, 2015 at 5:49
  • no, it just return "Array" Commented Sep 22, 2015 at 5:50

2 Answers 2

4

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)

Sign up to request clarification or add additional context in comments.

Comments

1

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)');
        }
    }
?>

1 Comment

Because $nampro is an array in query you can't use it directly. You have to mention index of array for value like $nampro[0].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.