mysql - PHP: How to grab an array checkbox value and then insert each individual result into a database query? -
i have form has checkbox list generated dynamically: name="cursoid[]"
each value correspond cursoid ($curso['cursoid']
), value taken mysql select
query shows me list of items ids.
the user may select n number of items, , need take each 1 of (ie. $cursoid = $_post['cursoid'];
) in order save them insert
query.
in form, generate each item while loop:
<?php $conectar = mysqli_connect(host, user, pass, database); $query = " select cursoid, nombrecurso, cursofechainicio, modalidadcurso, estadocurso cursos estadocurso='abierto'"; $buscarcurso = mysqli_query($conectar,$query); echo '<div class="checkbox">'; while ($curso=mysqli_fetch_assoc($buscarcurso)) { echo '<input type="checkbox" name="cursoid[]" value="'.$curso['cursoid'].'">'.$curso['nombrecurso']; } echo '</div>'; ?>
my database consultation in order insert field simple select:
insert cursosusuarios (userid, cursoid) values ('$userid', '$cursoid')
i have no issues $userid, single value.
how may use $cursoid = $_post['cursoid']
add database? i've been reading other questions (like this one, or this other one), couldn't manage apply case, don't know how insert database.
there's 2 main ways can insert variable amount of data database:
- build query dynamically (if have many columns, , don't know how many you'll update)
like so:
$fields = array(); $values = array(); $fields[] = 'field1'; $fields[] = 'field2'; ... $values[] = 1; $values[] = 2; ... $query = 'insert table (' . implode(', ', $fields) . ') values (' . implode(',', $values) . ')'; // execute $query
or:
- add individual items in separate queries, repeat on , on (if need fill variable amount of rows).
like (if checkboxes named "cursoid[]", corresponding post variable array, , can use that'll work arrays):
$userid_int = (int)$userid; foreach ($_post['cursoid'] $singleid) { $singleid_int = (int)$singleid; // execute: insert cursosusuarios (userid, cursoid) values ('$userid_int', '$singleid_int') }
however, careful - @ moment, code vulnerable sql injections (for example, if $_post['cursoid'] set
'; drop database x
you might - depending on configuration - allow lot of nasty stuff, ranging bypassing logins removing database. such, recommend taking step , looking how can parameterize queries, don't have worry hostile visitor injecting data in sql query. see, example, this answer.
Comments
Post a Comment