Hi,

I'm very new to PHP but slowly getting there... I need help with querying a dB from choices taken from checkboxes. 'foreach' doesn't want to work for me with this either! Once I've found out how to pass the checked box info on to another page I'll then find a way to use it to query the dB.

Here's the code I'm using:

$ams = mysql_query("SELECT amID, amenity FROM amenities");
while ($am = mysql_fetch_array($ams)) {
$amID = $am["amID"];
$amenity = $am["amenity"];
echo ("<input type='checkbox' name='ams[]' ".
"value='$amID'>$amenity$nbsp\n");
}
if ($ams == "") $ams = array();
?>
<br><input type="submit" name="Submit" value="Submit">
</form>
<?php
if (isset($_POST['submit'])){

foreach($_POST['checkbox'] as $ID) {
echo ("<p>Value: $ID<br><p>\n");
}
}

Thanks all
Klyve

    Not so much of an error as being at a loss!! I've now managed to pass the values to another page and it works fine. Now I want the passed values to be added to a mysql query.
    Klyve

      Dynamically created checkboxes, like text fields and other form elements, need to have unique name/value pairs, which I suspect is not happening in your code. If the name/value pairs are not unique, when the form is submitted the value from last form element with the non-unique name will be used by your data-processing script.

      You're selecting the 'amID' and 'amenity' columns from the database table 'amenities'. (I'll assume that each row has a unique amID value; though that may not necessarily be true.)

      // Build the query:
      $query = "SELECT amID, amenity FROM amenities";
      
      // Get a result identifier:
      $result = mysql_query($query);
      
      // Make sure there's a result identifier:
      if($result) {
      	// I'll use _fetch_row() instead of _fetch_array() since there's a short, easy-to-manage column list in the result set:
      	while($data = mysql_fetch_row($result)) {
      
      	// To assure that each name/value pair is unique, we'll stick 'amenity_' at the beginning of each check box name.
      	// Then we'll stick the 'amID' value for each amenity onto the end of the name.
      	// The 'value' of the amenity will be the 'amID' value:
      	printf("%s: <input type=\"checkbox\" name=\"amenity_%s\" value=\"%s\"><br />",$data[1], $data[0], $data[0]);
      }
      
      // D'OH! Almost fergot... free up the resources from yer result set:
      mysql_free_result($result);
      }
      
      // stick the rest of yer form in here... 
      

      Now, to 'extract' the values of the 'selected' amenities once the form is submitted, just loop through the $_POST vars (or $HTTP_POST_VARS, if you're using a version of PHP prior to 4.1.x):

      // start an array for each user-world selected 'amenity':
      $amens = array();
      
      // loop thru the $_POST vars:
      while(list($k,$v)=each($_POST)) {
      
      // If the 'key' starts with amenity, add the 'value' to the array of selected amenities:
      if(ereg("^amenity_", $k)) {
      	$amens[$k] = $v;
      }
      }
      
      // now you should all of the selected amenities from the form inside an array named $amens.
      // Do whatever you need to do with those selected values...
      

      Got it? Kinda? Sorta?

        the previous answer is not completely right. You can have checkboxes with the same name which will be passed as an array after submission if the name ends with [].

        <input type="checkbox" name="myname[]" value="X">Value1
        <input type="checkbox" name="myname[]" value="Y">Value2

        Will be returned as the array $myname where $myname[0] is the value of the first checkbox which is checked, $myname[1] of the second etc. mind that the first checkbox which is checked can be the second one on your form !

          Originally posted by nightowl
          the previous answer is not completely right. You can have checkboxes with the same name which will be passed as an array after submission if the name ends with [].

          I honestly didn't know that, nightowl. Thanks for the info. And I think of all those times I handled simiilar situations the other way...

          Now I've gotta go try it...

            that's what this BB is for and that's your "reward" fro trying to help people out: you learn something yourself too 😉

              This has all been v. helpful and m slowly picking this up... I have now managed to pass the checkbox values on and added them to my query as below:

              if (!$cats) {
              echo "No categories chosen";
              } elseif (!$ams) {
              echo "No amenities chosen";
              } else
              	{
              while(list($keyc, $cat) = each($cats))
              while(list($keya, $am) = each($ams))
              		{
              		$query =
              "SELECT villa.vID, vName, vAdd1, vTown, vCountry FROM `villa`, `catlookup`, `amenlookup` WHERE catID=$cat AND amenID=$am AND villa.vID=catlookup.vID AND villa.vID=amenlookup.vID";
              	$result = mysql_query($query);
              		}
              if ($row = mysql_fetch_array($result)) {
              while ($row = mysql_fetch_array($result))
              		{
              	$vID = $row["vID"];
              	$vName = stripslashes($row["vName"]);
              	$vAdd1 = $row["vAdd1"];
              	$vTown = $row["vTown"];
              	$vCountry = $row["vCountry"];
              		}
              			echo "<p><br><strong>$vName</strong><br>$vAdd1<br>$vTown<br>$vCountry<hr></p>";
              		} else {
              		echo "No Matches Found<br />Please try again";
              				}
              		}[code=php]
              But sometimes it works ok, sometimes it matches when it shouldn't and sometimes doesn't match when it should!

                I've just discovered that this repeats the SELECT statement for each checkbox value.... except it only picks up the different values for $ams - $cat remains the first value throughout.

                  Write a Reply...