0

I want to Insert data using foreach loop and the thing is I want to foreach loop two arrays simultaneously however in the code I got so far it there are duplicates in the database after insertion. So far,this is the php code I got for inserting:

    <?php 
include('dbcon.php');
if (isset($_POST['submit'])){
$month = $_POST['month'];
$guard = $_POST['guard_id'];
$time = $_POST['time_id'];

$area1 =  $_POST['aream'];
$area2 =  $_POST['areat'];
$area3 =  $_POST['areaw'];
$area4 =  $_POST['areath'];
$area5 =  $_POST['areaf'];

$m = $_POST['m'];
$t = $_POST['t'];
$w = $_POST['w'];
$th = $_POST['th'];
$f = $_POST['f'];





    foreach($area1 as $aream)
    {                       
//monday sched
foreach ($m as $daym){

    //check conflict

                $query=mysql_query("select *,COUNT(*) as count from gov_sched 
                natural join member natural join time where guard_id='$guard' and gov_sched.time_id='$daym' and area='$aream' 
                and day='m' and month='$month'")or die(mysql_error());
                    $row=mysql_fetch_array($query);
                    $count=$row['count'];
                    $time1=date("h:i a",strtotime($row['time_in']))."-".date("h:i a",strtotime($row['time_out']));
                    $guard1=$row['lastname']." ".$row['firstname'];
                    $area1=$row['area'];

                $queryt=mysql_query("select * from member where member_id='$guard'")or die(mysql_error());
                        $rowt=mysql_fetch_array($queryt);
                        $guardt=$rowt['lastname']." ".$rowt['firstname'];

                $querytime=mysql_query("select * from time where time_id='$daym'")or die(mysql_error($con));
                        $rowt=mysql_fetch_array($querytime);
                        $timet=date("h:i a",strtotime($rowt['time_in']))."-".date("h:i a",strtotime($rowt['time_out']));    


                if ($count==0)
                {

                    mysql_query("INSERT INTO gov_sched(month,guard_id,area,time_id,day) VALUES ('$month','$guard','$aream','$daym','m')")or die(mysql_error());

                    echo "<span class='text-success'>$month $timet $guardt at $aream every Monday successfully added!</span><br>";    
                }            
                else{

                    echo "<span class='text-danger'>$month $time1 is already taken by $guard1 at $aream every Monday </span><br>";

                }

            }
        }



              foreach($area2 as $areat)
    {        


    foreach ($t as $dayt){
    //check conflict
         $query=mysql_query("select *,COUNT(*) as count from gov_sched 
            natural join member natural join time where guard_id='$guard' and gov_sched.time_id='$dayt' and area='$areat' 
            and day='t' and month='$month'")or die(mysql_error());
                $row=mysql_fetch_array($query);
                $count=$row['count'];
                $time1=date("h:i a",strtotime($row['time_in']))."-".date("h:i a",strtotime($row['time_out']));
                $guard1=$row['lastname']." ".$row['firstname'];
                $area1=$row['area'];

            $queryt=mysql_query("select * from member where member_id='$guard'")or die(mysql_error());
                    $rowt=mysql_fetch_array($queryt);
                    $guardt=$rowt['lastname']." ".$rowt['firstname'];

            $querytime=mysql_query("select * from time where time_id='$dayt'")or die(mysql_error($con));
                    $rowt=mysql_fetch_array($querytime);
                    $timet=date("h:i a",strtotime($rowt['time_in']))."-".date("h:i a",strtotime($rowt['time_out']));    


            if ($count==0)
            {
                mysql_query("INSERT INTO gov_sched(month,guard_id,area,time_id,day) VALUES ('$month','$guard','$areat','$dayt','t')")or die(mysql_error());

                echo "<span class='text-success'>$month $timet $guardt at $areat every Tuesday successfully added!</span><br>";    
            }            
            else{

                echo "<span class='text-danger'>$month $time1 is already taken by $guard1 at $areat every Tuesday </span><br>";

            }

        }
    }


            foreach($area3 as $areaw)
{

        foreach ($w as $dayw){
    //check conflict
    $query=mysql_query("select *,COUNT(*) as count from gov_sched 
    natural join member natural join time where guard_id='$guard' and gov_sched.time_id='$dayw' and area='$areaw' 
    and day='w' and month='$month'")or die(mysql_error());
        $row=mysql_fetch_array($query);
        $count=$row['count'];
        $time1=date("h:i a",strtotime($row['time_in']))."-".date("h:i a",strtotime($row['time_out']));
        $guard1=$row['lastname']." ".$row['firstname'];
        $area1=$row['area'];

    $queryt=mysql_query("select * from member where member_id='$guard'")or die(mysql_error());
            $rowt=mysql_fetch_array($queryt);
            $guardt=$rowt['lastname']." ".$rowt['firstname'];

    $querytime=mysql_query("select * from time where time_id='$dayw'")or die(mysql_error($con));
            $rowt=mysql_fetch_array($querytime);
            $timet=date("h:i a",strtotime($rowt['time_in']))."-".date("h:i a",strtotime($rowt['time_out']));    


    if ($count==0)
    {
        mysql_query("INSERT INTO gov_sched(month,guard_id,area,time_id,day) VALUES ('$month','$guard','$areaw','$dayw','w')")or die(mysql_error());

        echo "<span class='text-success'>$month $timet $guardt at $areaw every Wednesday successfully added!</span><br>";    
    }            
    else{

        echo "<span class='text-danger'>$month $time1 is already taken by $guard1 at $areaw every Wednesday </span><br>";

    }

   }
}



foreach($area4 as $areath)
                {
            foreach ($th as $dayth){
    //check conflict

                            $query=mysql_query("select *,COUNT(*) as count from gov_sched 
                            natural join member natural join time where guard_id='$guard' and gov_sched.time_id='$dayth' and area='$areath' 
                            and day='th' and month='$month'")or die(mysql_error());
                                $row=mysql_fetch_array($query);
                                $count=$row['count'];
                                $time1=date("h:i a",strtotime($row['time_in']))."-".date("h:i a",strtotime($row['time_out']));
                                $guard1=$row['lastname']." ".$row['firstname'];
                                $area1=$row['area'];

                            $queryt=mysql_query("select * from member where member_id='$guard'")or die(mysql_error());
                                    $rowt=mysql_fetch_array($queryt);
                                    $guardt=$rowt['lastname']." ".$rowt['firstname'];

                            $querytime=mysql_query("select * from time where time_id='$dayth'")or die(mysql_error($con));
                                    $rowt=mysql_fetch_array($querytime);
                                    $timet=date("h:i a",strtotime($rowt['time_in']))."-".date("h:i a",strtotime($rowt['time_out']));    


                            if ($count==0)
                            {
                                mysql_query("INSERT INTO gov_sched(month,guard_id,area,time_id,day) VALUES ('$month','$guard','$areath','$dayth','th')")or die(mysql_error());

                                echo "<span class='text-success'>$month $timet $guardt at $areath every Thursday successfully added!</span><br>";    
                            }            
                            else{

                                echo "<span class='text-danger'>$month $time1 is already taken by $guard1 at $areath every Thursday </span><br>";

                            }

                        }
                    }

 foreach($area5 as $areaf)
                    {

                foreach ($f as $dayf){
    //check conflict

                                $query=mysql_query("select *,COUNT(*) as count from gov_sched 
                                natural join member natural join time where guard_id='$guard' and gov_sched.time_id='$dayf' and area='$areaf' 
                                and day='f' and month='$month'")or die(mysql_error());
                                    $row=mysql_fetch_array($query);
                                    $count=$row['count'];
                                    $time1=date("h:i a",strtotime($row['time_in']))."-".date("h:i a",strtotime($row['time_out']));
                                    $guard1=$row['lastname']." ".$row['firstname'];
                                    $area1=$row['area'];

                                $queryt=mysql_query("select * from member where member_id='$guard'")or die(mysql_error());
                                        $rowt=mysql_fetch_array($queryt);
                                        $guardt=$rowt['lastname']." ".$rowt['firstname'];

                                $querytime=mysql_query("select * from time where time_id='$dayf'")or die(mysql_error($con));
                                        $rowt=mysql_fetch_array($querytime);
                                        $timet=date("h:i a",strtotime($rowt['time_in']))."-".date("h:i a",strtotime($rowt['time_out']));    


                                if ($count==0)
                                {
                                    mysql_query("INSERT INTO gov_sched(month,guard_id,area,time_id,day) VALUES ('$month','$guard','$areaf','$dayf','f')")or die(mysql_error());

                                    echo "<span class='text-success'>$timet $guardt at $areaf every Friday successfully added!</span><br>";    
                                }            
                                else{

                                    echo "<span class='text-danger'>$time1 is already taken by $guard1 at $areaf every Friday </span><br>";

                                }

                            }
                        }
}
?>  

I think this way of using foreach loop isnt fit to my insertion of data so any help I could get there please? thanks in advance.

User
  • 1
  • 2
  • The array you are using to iterate is empty (boolean) or another value other than an array on line 15. Just figure out why that is not an array. – Rasclatt Sep 03 '17 at 14:54
  • the start of the first for each loop is line 15. how do I know it's an array? – User Sep 03 '17 at 14:59
  • Well presumably it's saying `$area` is supposed to be an array? If it's not an array, then you can't use `foreach()` on it. Use `if(!is_array($area)) { print_r($area); die('Not an array'); }` before the `foreach()`. – Rasclatt Sep 03 '17 at 15:14
  • @Rasclatt Will it still iterate and insert the data into the database? because it is from multiple dropdowns populated by data from database. – User Sep 03 '17 at 15:19
  • No, not in my snippet cause it dies. I don't know what your script is doing, you can check if array and then display whatever inside that `if` block. – Rasclatt Sep 03 '17 at 15:22
  • Also, your mysql issue is two-fold. You should convert over to `mysqli_*` from `mysql_*` and then deal with injection itself after that as you noted. – Rasclatt Sep 03 '17 at 15:24
  • Possible duplicate of [Invalid argument supplied for foreach()](https://stackoverflow.com/questions/2630013/invalid-argument-supplied-for-foreach) – Rasclatt Sep 03 '17 at 15:37
  • So you're telling that I should look into the value inside the $area? Isn't there any other way to deal with it? beacause I've been debugging this for 3 days. – User Sep 03 '17 at 15:45
  • The problem you are having is that you are passing `$area` into your `foreach()` iterator. If `$area == ''` or `$area == false;` or `$area == true;` or `$area == 'whatever';` you will not be able to loop through it, which is why you are getting an error on the `foreach`. `$area` has to be an array or object to loop through. – Rasclatt Sep 03 '17 at 15:49
  • Oh I get what you mean, but how should I convert it into an array, since it is what I needed.? and the values should be from the drop downs. – User Sep 03 '17 at 15:51
  • Since `$area = $_POST['area'];` then you have to figure out what `$_POST['area'];` is and why it's not an array. – Rasclatt Sep 03 '17 at 15:54
  • so that way it should work? or maybe another problem will occur? – User Sep 03 '17 at 15:57
  • Also to help you, I suggest you create a series of functions that wrap each action. That way, you can make the script easier to read and trouble shoot. So you should have a function like `getMemberById($id)` that runs the sql and returns the results where you feed the id and mysql connection (when you switch to a proper connection) into it. That way you would do `$memberById = getMemberById($id);` and get back an array and you can reuse it else where, if need be. – Rasclatt Sep 03 '17 at 15:58
  • What is `$_POST['area']`? From a form I assume, but it would have to be an arrayed named form like ``. That way the `$area` will be an array, but I don't know what your app is supposed to do, so I can't really guide more than that – Rasclatt Sep 03 '17 at 16:00
  • do you mean prepared statements? well thanks anyways. maybe my problem is too easy for you that you're just giving me hints I'll just fix it myself. anyway @Rasclatt thank you. – User Sep 03 '17 at 16:01
  • No, it's not too easy, it more is that I don't know what your application does, so I don't know what `$_POST['area']` is, so it's possible it's your form that is the problem, or it's that you think it's supposed to do something other than what it really does. – Rasclatt Sep 03 '17 at 16:03
  • The main problem I see is that you have too much procedural code and need to break it into working functions (or class/methods if you have knowledge there). – Rasclatt Sep 03 '17 at 16:04
  • Instead of creating a whole bunch of code and then testing it at the end, you need to start easy. Make a function that will return results you need if you manually put a value in, then when that works, you have solved that issue. Then you apply that new function into a scenario where it get's it's value from the post, not manually. Then if that works, you expand that out and keep going until it all works. – Rasclatt Sep 03 '17 at 16:08
  • I'lljust look into it again. If you have still time would you mind looking into my code for the dropdowns I posted the wrong code earlier. @Rasclatt – User Sep 03 '17 at 16:27

1 Answers1

1

you are naming dropdowns as area_id. if you are expecting $_POST['area'] from this html then you must change it to $_POST['area_id'];

EDITED you can loop $m and $area at the same. eg

$i=0;
foreach($m[0] as $a){
    echo $a[0];
    echo $area[0][$i];
    $i++;
}

in this example array size must be same.. else it throw a error.

EDITED you can loop a array like this .

 $maxLength = count($m[0]) > count($area[0]) ? count($m[0]) : count($area[0]);
        for($i = 0; $i < $maxLength; ++$i){
         $ma = array_key_exists($i, $m[0]) ? ' '. $m[0][$i] : "";  
         $a= array_key_exists($i, $area[0]) ? ' '. $area[0][$i] : "";
          echo "$ma $a <br/>";
     }

let me know if it didn't work.

Mahmood Sanjrani
  • 108
  • 3
  • 19
  • Comments are not for extended discussion or debugging sessions. If you are still having trouble and need to add more information, edit the question. Mahmood can then update his answer. – Cody Gray - on strike Sep 08 '17 at 16:09