Jump to content

fetch value from HTML form's check box


phppaper

Recommended Posts

Hello,

 

I have a check box from HTML form and I would like to used the selected values from the check box to get data from MYSQL database with PHP.

 

the form is like this:

<input type="checkbox" name="a" value="red">red

<br>

<input type="checkbox" name="a" value="green">green

<br>

<input type="checkbox" name="a" value="yellow">yellow

 

How do you fetch those values if red and green are selected with PHP and run the query to the Mysql to fetch data where a field is equal to red or green??

 

thanks!

 

Link to comment
https://forums.phpfreaks.com/topic/191963-fetch-value-from-html-forms-check-box/
Share on other sites

As these are checkboxes, not radio buttons, you can either give them each their own name, or define them in an array like name="a[]"

 

If you chose the former approach then each checkbox will be available in the post or get array by name, or with the second approach you will need to extract them from the array

Ok assume you used the second approach and your form looks like this

 

<input type="checkbox" name="a[]" value="red">red
<br>
<input type="checkbox" name="a[]" value="green">green
<br>
<input type="checkbox" name="a[]" value="yellow">yellow

 

I must further assume that you are submitting this form by method="post" so therefore your resultant array will be in $_POST['a']

 

so $_POST['a'] will be an array and if you put print_r($_POST['a']); in your code, you will see all the selected values.

 

What you do with that data regarding contacting your database, depends on if you want to look up information or store information based on the choices, and also depends on the structure of your database, so you need to supply more information

example my database has 1 column called color and it store all the color:

 

table "atable" has Column "color":

 

color

-------------------------

red

green

yellow

grey

 

and if people selected red and green from the form,

 

how is the PHP going to be inorder to select the data where color == green or color == red??

 

Thanks!

So your query would be built something like this.

 

$cond = '';
if(is_array($_POST['a']))
{
      foreach($_POST['a'] as $selected_colour)
      {
            $cond .= ($cond == '')?' where color='.$selected_colour:' or colour='.$selected_colour;
      }
}
$query = sprintf("select * from atable %s",$cond);

 

then you can run that query and process the results

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.