简体   繁体   中英

how to validate a form submit in php

I have a form like this:

<form method="post" action="">
<?php
$h = mysql_query("select distinct sous_sous_categorie, sous_sous_categorie_url  
                  from articles where sous_categorie_url='".$_GET["s_cat"]."' ");
while($hRow=mysql_fetch_assoc($h)){  
?>
    <span class="submit">
    <input type="checkbox" name="<?php echo $hRow["sous_sous_categorie_url"]; ?>" 
     value="<?php echo $hRow["sous_sous_categorie_url"]; ?>" />&nbsp;&nbsp;
    <a href="?categorie=<?php echo $_GET["categorie"];  ?>&s_cat=<?php echo $_GET["s_cat"]; ?>&s_s_cat=<?php echo $hRow["sous_sous_categorie_url"];  ?>"><?php echo $hRow["sous_sous_categorie"];  ?></a>
    </span>
<?php } ?>
<input type="submit" name="submit_sous_sous_categorie_search" 
 value="search" class="submit" />
</form>

as you can see the form is in a loop, the form consists of checkboxes that user will check and accoding to this a search query will be made, the thing is that checkboxes have the name attribute but this attribute is variable (because it is fetch from the db) so my question is how can I make this:

if(checkboxes are empty){
    echo "you must at least select one checkbox"
}

This is just an example but I dont see how to do a simple thing such as

if(!$_POST["checkbox"]}{
    echo "you must at least select one checkbox";
}

Again, because the name of the checkboxes are variable.

You can make your checkboxes into an array by changing the name to:

name="checkboxes[<?php echo $hRow["sous_sous_categorie_url"]; ?>]"

Then you can use code like this to make sure at least one is checked:

$passed = false;
if( isset( $_POST['checkboxes'] ) && is_array( $_POST['checkboxes'] ) )
{
    foreach( $_POST['checkboxes'] as $k => $v )
    {
        if( $v )
        {
            $passed = true;
            break;
        }
    }
}

if( ! $passed )
{
    echo "You must select at least one checkbox";
    exit();
}

Also, you should be careful with your query there, you need to escape that to prevent SQL injection.

You can pass arrays from your FORM to the PHP script:

<!-- The brackets [] let PHP know you're passing in an array -->
<input type="checkbox" name="categories[]" value="<?php echo $hRow["sous_sous_categorie_url"]; ?>" />

Then in the script:

// $_POST['categories'] is an array when categories are checked.
if (empty($_POST['categories'])) {
  echo 'Please select a category.';
} else {
  foreach ($_POST['categories'] as $url) {
     // do something with $url
  }
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM