-2

my code is not working it's showing error in condition.

 <?
 foreach($_POST['check'] as $value )   
 foreach($_POST['emp'] as $value2 )     
 { 
 mysql_query("insert into tb_recived_jobs set job_id='$value'emp_id='$value2'");  
 }     
 ?>
  • [`mysql_*` functions are deprecated and will soon be removed. Please use `mysqli_*` or PDO instead.](http://stackoverflow.com/a/20767765/1612146) – George Jan 06 '14 at 12:15
  • is $_POST['check'] is an array? – R R Jan 06 '14 at 12:15
  • You should consider building one large query with string concatination. An extra query for every row is very unperformant and can make your page/script very slow. – Steini Jan 06 '14 at 12:15
  • Nested foreach creates a cross-product. I don't think that's what you really want. The error you're getting has nothing to do with `foreach`, it's probably because you left out the `,` between the variables in the SQL. – Barmar Jan 06 '14 at 12:17
  • What is the exact error message you're getting? – Barmar Jan 06 '14 at 12:18
  • It's always a good idea to wrap the bodies of your `foreach` with `{}`, even if it's one line. – Barmar Jan 06 '14 at 12:20

4 Answers4

1

You should use For loop to do this

$count = count($_POST['check']);

for($i=0;$i<=$count;$i++) {
    $value= $_POST['check'][$i];
    $value2= $_POST['emp'][$i];
    mysql_query("insert into tb_recived_jobs(job_id,emp_id) values('$value','$value2')"); 
}
Manish Jangir
  • 5,329
  • 4
  • 42
  • 75
1

correct your SQL Query like this :

"insert into tb_recived_jobs set job_id='$value' emp_id='$value2'"

you are missing one space between first value and second column, make an INSERT SQL query like this one helps much more:

"INSERT INTO `tb_recived_jobs` (`job_id`, `emp_id`) VALUES ('$value', '$value2');"

UPDATE: I just realized what is wrong exactly, cause here you have two arrays and you want to insert their values by a query, in this case both arrays should have same length to everything goes well

$checks = $_POST['check'];
$emps = $_POST['emp'];

$length = count($checks);
if ($length === count($emps)) {
    for ($i = 0; $i < $length; $i++) {
        $sql = "INSERT INTO `tb_received_jobs` (`job_id`, `emp_id`) VALUES ('{$checks[$i]}', '{$emps[$i]}');";
        //  send the query
    }
}

this should work properly.

PRAISER
  • 793
  • 7
  • 15
0

You can merge two array $_POST['check'] and $_POST['emp'] in one array after than you can use foreach for this.

Avish Shah
  • 111
  • 7
0

try this as i understand if you want to insert each $_POST['emp'] for every $_POST['check']

<?
foreach($_POST['check'] as $value ) 
{  
 foreach($_POST['emp'] as $value2 )     
 { 
    mysql_query("INSERT INTO `tb_recived_jobs`(job_id, emp_id) VALUES('$value', '$value2')") or die(mysql_error());  
 } 
}    
 ?>
Satish Sharma
  • 9,547
  • 6
  • 29
  • 51