Hello and thanks in advance to anyone who can help me with my array problem. I've always struggled with arrays, and now I Need to understand how I can use them to solve my latest problem. I've created a test scenario to recreate what I'm trying to do in real-life.
In my test scenario, the input page 'in.php' I give the user a form to check their favorite colors. The form uses checkboxes. I would like to take the checkbox values and store them as an array.
So if the user checks off the colors red, blue and green, it would save the values '1','2', '3' as an array in the table 'users'.
And then in my 'out.php' I would like to unroll the array values and look up in the table 'colorkey' for each value in the array.
So for each user it would echo users.id and the list of colors they chose.
//create colorkey table
CREATE TABLE `arraytest`.`colorkey` (
`color_id` int(11) NOT NULL AUTO_INCREMENT,
`color` varchar(20) NOT NULL,
PRIMARY KEY (`color_id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8
INSERT INTO `arraytest`.`colorkey` VALUES (1,'red'),
(2,'Blue'),
(3,'Green'),
(4,'Yellow'),
(5,'Brown'),
(6,'Purple');
//create a users table
CREATE TABLE `arraytest`.`users` (
`id` int(2) NOT NULL AUTO_INCREMENT,
`colorarray` varchar(65) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=24 DEFAULT CHARSET=latin1;
in.php
<?php
$dbconnection // this is my db connection file.
$color = array();
if(isset($_POST['color'])){
$color = $_POST['color'];
}else{
$color = NULL;
}
$newcolor = implode(", ", $color);
if(isset($_POST['submit'])){
mysql_query("insert into users (colorarray) values ('{$newcolor}')")
or die('No Insert: ' .mysql_error());
HEADER("Location:out.php");
}
?>
<?php echo"<form action='{$_SERVER['PHP_SELF']}' method='post'> "; ?>
<input type='hidden' name='doit' value='yes'>
<input type='checkbox' name = 'color[]' value = '1'> Red <br />
<input type='checkbox' name = 'color[]' value = '2'> Blue <br />
<input type='checkbox' name = 'color[]' value = '3'> Green <br />
<input type='checkbox' name = 'color[]' value = '4'> Yellow <br/>
<input type='checkbox' name = 'color[]' value = '5'> Brown <br />
<input type='checkbox' name = 'color[]' value = '6'> Purple </p>
<p><input type='submit' value='submit' name='submit'>
//out.php
So here is my output page, and I don't know where to go next. I can echo out the id and their array values, but have no idea how to do a query like SELECT id, colorarray from users
inner join colorkey.color_id = users.colorarray
where id='$id'
//so that it would output the users_id and the list of colors they've chosen.
<?php
$dbconnection // this is my db connection file.
$id = getvar("id");
$colorarray =array();
$result = mysql_query("Select id, colorarray from users ");
while($row = mysql_fetch_array($result)){
echo"{$row['id']} | {$row['colorarray']}<br />";
}
Again, Thanks for taking the time to look at this and if you can point me in the correct direction I would be very grateful. Thank you.