1

how do I loop through this array and assign the values to a variable and save it to MySQL?

the following array was generated using this form. I don't want to use index keys as the number of values may increase or decrease.

<input type="text" name="formB[usr_f_name][]" placeholder="First Name" />
<input type="text" name="formB[usr_l_name][]" placeholder="Last Name" />
<input type="text" name="formB[usr_mobile][]" placeholder="Mobile Number" />






Array

(
    [usr_f_name] => Array
        (
            [0] => first
            [1] => second
        )

    [usr_l_name] => Array
        (
            [0] => 
            [1] => 
        )

    [usr_mobile] => Array
        (
            [0] => 
            [1] => 
        )

    [usr_email] => Array
        (
            [0] => 
            [1] => 
        )

)

This is what I have at the moment. but can't get it working

  $id_array = array_keys($_POST['formB']);
  foreach ($id_array as $id){
        $usr_f_name =  mysqli_real_escape_string ($_POST['usr_f_name'][$id]);
        $usr_l_name =  mysqli_real_escape_string ($_POST['usr_l_name'][$id]);
        $usr_mobile =  mysqli_real_escape_string ($_POST['usr_mobile'][$id]);
$sql = "INSERT INTO formB SET f_name = '$usr_f_name', l_name = '$usr_l_name', mobile  ='$usr_mobile'";
    }
2
  • where is $id_array coming from? Commented Oct 12, 2017 at 4:49
  • opps -- rectified ... Commented Oct 12, 2017 at 4:50

2 Answers 2

3

You can do something like

foreach ($_POST['formB']['usr_f_name'] as $id=>$value){//loop over the values of the usr_f_name and then use the index of that to get the other values
        $usr_f_name =  mysqli_real_escape_string ($_POST['formB']['usr_f_name'][$id]);
        $usr_l_name =  mysqli_real_escape_string ($_POST['formB']['usr_l_name'][$id]);
        $usr_mobile =  mysqli_real_escape_string ($_POST['formB']['usr_mobile'][$id]);
$sql = "INSERT INTO formB SET f_name = '$usr_f_name', l_name = '$usr_l_name', mobile  ='$usr_mobile'";
    }
Sign up to request clarification or add additional context in comments.

3 Comments

any other way beside looping? NO!
i mean to say any other looping methods.
@TheNagaTanker yes there other methods
0

Try this...

$array = array(     
    'usr_f_name'    => array('first','second'),
    'usr_l_name'    => array('',''),
    'usr_mobile'    => array('',''),
    'usr_email'     => array('',''),
);//Your array

$sql= '';
for($i=0;$i<count($array['usr_f_name']);$i++) 
$sql .= "INSERT INTO formB SET f_name = '".$array['usr_l_name'][$i]."', l_name = '".$array['usr_l_name'][$i]."', mobile  ='".$array['usr_mobile'][$i]."';";

Comments

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.