问题描述:

I have 2 checkboxes. Their values go to another php file and if any of them is checked, its value is inserted mysql codes. I did it, but when the number of checkbox increase and more advanced things appear, my code will be impossible to put into practise.

Here is checkbox.php :(it is inside a form)

<div>

<label>Choose:</label>

<label>Camera </label><input type="checkbox" name="kind[]" value="1" />

<label>Video </label><input type="checkbox" name="kind[]" value="2"/>

</div>

when the form is clicked, it goes to fetch_kind.php via AJAX and jquery($.post).

Here is code:

<?php

$kind = array();

$kind = $_POST['kind'];

$count = count($kind);

if ($count== 0) {

echo "You did not checked any of checkboxes!!!";

}

if ($count == 2) {

$sql = "SELECT id,kind FROM products";

} else {

foreach ($kind as $value) {

if ($value =="1") {

$sql = "SELECT id,kind FROM products WHERE kind = " . $value;

}

if ($value =="2") {

$sql = "SELECT id,kind FROM products WHERE kind = " . $value;

}

}

}

?>

Could you give a better example? Thank you...

网友答案:

A simple way would be to group all the values and us IN

if ($count > 0){
    $sql = "SELECT id,kind FROM products WHERE kind IN (" . implode (',', $kind) . ")"; 
}

Also you might want to look into sanitizing you input.

网友答案:

You can loop through all your checkboxes and add a simple condition to an array. You implode the array at the end.

Something like:

$conds = array();
foreach ($kind as $value) {
  $conds[] = '`kind` = ' . intval($value);
}

$sql = "SELECT id,kind FROM products WHERE " . implode(" OR ", $conds);
相关阅读:
Top