Forum Moderators: coopster

Message Too Old, No Replies

checkbox problem

         

Suzie17

4:19 pm on Mar 4, 2004 (gmt 0)

10+ Year Member



hi
I am relatively new to PHP and have been having a few problems with checkboxes.
I have a page with many checkboxes on it, the user can select more than one of them, once they have made their choice(s) they click a subscribe button this should then add the contents to a MySQL table.
The code i have at the moment looks like this:

/* Create form containing subscription selection list */
echo "<form action='sub.php' method='post'>\n";
echo "<table cellpadding='2' border='1'>";
$counter=1;
while ($row = mysql_fetch_array($result)) {
extract($row);
echo "<tr><td valign='top' width='15%'>\n";
echo "<input type='checkbox' name='interest[$Feed_Name]' value='$Feed_Name'\n";
if ( $counter == 1 ) {
echo "checked";
}
echo ">$Feed_Name
</td>
<td>$URL</td>
</tr>";

$counter++;
}

echo "</table>";

$query = "INSERT INTO feeds(Feed_ID, Feed_Name, URL, loginName) VALUES
('NULL','$Feed_Name','$URL','$loginName')";
echo $query;
$result = mysql_query($query);
if ($result) {
echo "hello";
} else {
echo ("Entry not added. There was a problem somewhere, fix it.");
}

It is the query beginning "INSERT INTO feeds" that is my problem, i need to find a way of picking up what checkboxes have been checked.
sorry for posting all my code, its just incase i dont explain myself very well.

any help would be much appreciated :-)
thank you

[edited by: jatar_k at 5:47 pm (utc) on Mar. 4, 2004]
[edit reason] trimmed code down [/edit]

ergophobe

5:39 pm on Mar 4, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Suzy,

Welcome to WebmasterWorld! Since you're new, you might check out the Charter [webmasterworld.com].

Basically, your checkboxes will only have values and be sent if they are checked. An easy way to see what is being sent is to put this at the very bottom of your page

if isset($_POST) {
echo "<pre>" . print_r($_POST, true) . "</pre>";
}

If post vars are set, this will give you a nice list of all values being sent. To access post vars named "var" you can't use $var as you are doing (unless your server has register_globals on, which it shouldn't) but must use $_POST['var'].

You can build your query like so

if isset($_POST['interest']) { /* anything chosen? */
foreach($_POST['interest'] as $key => $val) {
$query = "INSERT INTO feeds(Feed_ID, Feed_Name, URL, loginName) VALUES ('NULL','$key','$URL','$loginName')";
$result = mysql_query($query);
}
}
If you don't understand, look up "foreach" under control structures in the manual


sorry for posting all my code, its just incase i dont explain myself very well.

In general it helps everyone if you post only the code directly related to your problem, rather than page text, mysql connections and so forth.

Suzie17

7:08 pm on Mar 4, 2004 (gmt 0)

10+ Year Member



thats great! thank you for your help