I've got myself really confused over arrays and I hope someone might be able to help me some.
I'm trying to store users selections of various pictures in a mysql database ( up to 3 pictures to choose from at a time). The selections are in fact checkboxes below each picture and I want to store these selections as $pic_id's in an array.
The selections are getting stored in my database but it seems that they are not being assigned keys as I expected and I can't seem to use them.
I want to be able to use the picture id's to show the selections made.
This is my result: [7] => 11,6 [8] => 9,8
but I need to get at these variables individually. I would expect this: [7] => 11, [8] =>6, [8] => 9, [9] => 8
The form:
<form action="insert.php" method="GET">
<?php
<input type=\"checkbox\" name=\"pic_id[]\" value=".$row['id'].">
<input type="submit" name="submit" value="Add" />
?>
insert.php
$checkBox = implode(',', $_GET['pic_id']);
if (isset($_GET['submit'])) {
$sql="INSERT INTO pics (pic_id) VALUES ('" . $checkBox . "')";
Print Array
<?php
$sql="SELECT * FROM pics";
$query = mysqli_query($conn, $sql);
$myArray = Array();
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$myArray[]=$row['pic_id'];
}
print_r($myArray);
?>
See result above.
Just separate the values like you concatenated them when inserting in the database. Then loop through the results and add them to your array.
<?php
$sql="SELECT * FROM pics";
$query = mysqli_query($conn, $sql);
$myArray = array();
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
foreach(explode(',', $row['pic_id']) as $id) {
$myArray[]= $id;
}
}
print_r($myArray);
?>
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.