I am posting an array which will look something like this 4, 6, 7
I am having trouble inserting each of these values into an sql table though.
Here's what I have so far...
$a = array($_POST['newsletterArray']);
$mything = 32;
$values = array();
foreach($a as $key => $value) {
$values[] = "('{$mything}', '{$value}')";
}
if(sizeof($values)) {
$query = "INSERT INTO images (news_event_id, newsletter_id) VALUES ".implode(',', $values);
$result = $mysqli->query($query);
}
This code inserts the first record from the array but none of the subsequent records.
If I substitute $_POST['newsletterArray']
with 4, 6, 7
it works fine so it seems this is where the problem is.
newsletterArray
is a text input if that helps at all.
$a
and have a look! I could imagine$_POST['newsletterArray']
being an array itself, as it might be the result of checkboxes being posted as part of a form submission. In that case use$a=$_POST['newsletterArray']
. Otherwise you get an array holding an array inside $a which does not make sense for your foreach loop. So, clearly the fist step: what is the value of$_POST['newsletterArray']
? – arkascha Nov 19 '12 at 0:514, 6, 7
and want to use thatstring
as an array? That is something different. Your code gives you an array holding a single element of typestring
, so array("4, 6, 7"), that is completely different from array(4,6,7). Instead you have to 'explode' the string into separate elements and clear those afterwards:$a=explode(',',$_POST['newsletterArray']);for($i=0; $i<count($a);$i++)$a[$i]=(integer)trim($a);
. – arkascha Nov 19 '12 at 9:04