简体   繁体   中英

Insert array from form to sql

I have a form that someone can add multiple phone numbers and extension, and I am trying to save them in the database, whenever I save the data it shows the word "Array" in both filed.

Here is my code so far:

if (!empty($_POST['Phone']) && isset($_POST['Extension'])) {
foreach ($_POST['Phone'] as $key => $value) {
    foreach ($_POST['Extension'] as $key => $value2) {
        $para = array("UserID" => \PDO::PARAM_INT, "Phone" => \PDO::PARAM_STR, "Extension" => \PDO::PARAM_STR);
        $val = array($_SESSION['UserID'], $_POST['Phone'], $_POST['Extension']);
        $r = DB::Call("[spPhoneInsert]", $para, $val);           
    }
}

if (count($r) > 0 && $r[0]['Result'] == 'Ok') {
    header("location:home.php?added_phone=1");
} else {
    header("location:home.php?error_phone=1");
}
exit;
}

whenever you post a form with multiple same name elements like

<input type="text" name="phone[]">
<input type="text" name="phone[]">

data is posted as array to the action page. You have to loop through this array to save them in data base

you can loop like this and create whatever format you want Following code will save your number and extension comma seprated

    foreach ($_POST['phone'] as $number){
    $allNumbers .= $number.',';
    }
foreach ($_POST['extension'] as $ext){
    $allExt .= $ext.',';
    }
  $para = array("UserID" => \PDO::PARAM_INT, "Phone" => \PDO::PARAM_STR, "Extension" => \PDO::PARAM_STR);
        $val = array($_SESSION['UserID'], trim($allNumbers,','), trim($allExt,','));
        $r = DB::Call("[spPhoneInsert]", $para, $val); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM