i’m confused … I am encountering a tiny issue that drives me crazy. I have arrays in an array which i’d like to insert into an SQL table. My issue is that i don’t figure out how to insert arrays in an array …
The arrays: Array ( [1] => Array ( [diploma] => Master [institut] => IAE ) [2] => Array ( [diploma] => Licence [institut] => Université ) )
Any piece of advice is welcome 🙂 Thanks a lot from France !
<input id="mytext-{cid}" type="text" name="training[{cid}][diploma]" placeholder="Diplôme" value=""> <input name="training[{cid}][institut]" placeholder="Institut"> try { $pdo = new PDO('mysql:host='.$host.';dbname='.$bd, $login, $password); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ); } catch (Exception $e) //Le catch est chargé d’intercepter une éventuelle erreur { die ($e->getMessage()); } global $pdo; // INSERT MySQL if (empty($_POST['training'])){ } else { $sql = "INSERT INTO user_resume (Diplome,Institut) VALUES (?,?)"; $stmt= $pdo->prepare($sql); $stmt->execute($_POST['training']); }
Advertisement
Answer
You need to loop over your multidimensional array and use named placeholders so the values match up.
$sql = "INSERT INTO user_resume (Diplome, Institut) VALUES (:diploma, :institut)"; $stmt= $pdo->prepare($sql); foreach($_POST['training'] as $params){ $stmt->execute($params); }