Checkbox based sql query

Hi friends
It is my first post on SitePoint.I hope i will get solutions for my posts & will learn from SP.

In my mysql database I have 11 columns. First is Sr_No (Auto Increment) & others are named from A to J. Now the problem is 1 user wants to get all rows from column A,C,E & another user want to get all row from column B,D,F,G,I. I have created 10 checkboxes. Now how can i get only columns which users select from checkboxes. I hope I explained my query correctly.
Please help.



You could try something like this?

if(isset($_GET['submit']) && $_GET['submit']=='1'){
  $query = "SELECT ";

    while($i < '5'){
        $query .= $i.',';
    $query = substr($query, 0, -1); //remove last comma
    $query .= " FROM table";
    if($input === true){
      //$result = mysql_query($query);
      echo 'You must select something!';



  echo '<form action="test.php?submit=1" method="post">';
  echo '1: <input type="checkbox" name="1" value="option1"><br />';
  echo '2: <input type="checkbox" name="2" value="option2"><br />';
  echo '3: <input type="checkbox" name="3" value="option3"><br />';
  echo '4: <input type="checkbox" name="4" value="option4"><br />';
  echo '<input type="submit" name="submit" value="Submit Query" />';
  echo '</form>';

I’m not sure if theres another way to achieve what you need, but this would work.

I would use a form like this:

<form action="" method="post">
<label><input type="checkbox" name="col[]" value="a">a</label><br>
<label><input type="checkbox" name="col[]" value="b">b</label><br>
<label><input type="checkbox" name="col[]" value="c">c</label><br>
<label><input type="checkbox" name="col[]" value="d">d</label><br>
<label><input type="checkbox" name="col[]" value="e">e</label><br>
<label><input type="checkbox" name="col[]" value="f">f</label><br>
<label><input type="checkbox" name="col[]" value="g">g</label><br>
<label><input type="checkbox" name="col[]" value="h">h</label><br>
<label><input type="checkbox" name="col[]" value="i">i</label><br>
<label><input type="checkbox" name="col[]" value="j">j</label><br>
<input type="submit" name="submit" value="Submit">

and php like this:

if (is_array($_POST['col'])) {
    $sql = "SELECT ";
    foreach($_POST['col'] AS $value) {
        $sql .= "{$value}, ";
    $sql  = substr($sql, 0, -2);
    $sql .= " FROM table";
    echo "sql= " . $sql . "<br /><br />\
} else {
    echo "No column was selected<br /><br />\

of course, instead of the echo, you would use a mysql query :wink:

thanks captainccs & thanks Steveiwonder for your quick & valuable replies

A piece of advice, which will make your life a lot easier six months after you finish the script:

Name your database tables something other than A through J. Give them names that actually apply to the data they hold, because it’s thoroughly painful to try and divine what you were thinking the first time around.

thanks for precious advice brother. I will take care of this… :slight_smile: