0

i am working on my generate report code in php, i having problem if i checked multiple checkbox in my form.

Here is my sample html code.

<input type="check" name="permit" value="Locational Clearance"/>Locational Clearance
    <input type="check" name="permit"  value="PALC"/>PALC
    <input type="check" name="permit"  value="DP"/>DP
    <input type="check" name="permit"  value="AP"/>AP

and this is my query.

<?php
    $servername = "localhost";
    $username = "root";
    $password = "";



    $year = $_POST['year'];
    $permit = $_POST['permit'];
    $range_to = $_POST['range_to'];
    $range_from = $_POST['range_from'];
    $comma_separated_permits = implode(",", $permit);
    // Create connection
    $conn = mysql_connect($servername, $username, $password);
    // Check connection
    if(! $conn )
    if(! $conn )
{
  die('Could not connect: ' . mysql_error());
}
$sql = "SELECT  permit_type, count(id) as 'no',DATE_FORMAT(date,'%M %Y') as 'month', sum(total_amount) as 'amount'     
        FROM payments
        WHERE date like '%$year%' and permit_type IN ('$comma_separated_permits')
        group by DATE_FORMAT(date,'%M')
        order by DATE_FORMAT(date,'%m')";

mysql_select_db('cpdo_db');
$result = mysql_query( $sql, $conn );
if(! $result )
{
  die('Could not get data: ' . mysql_error());
}
?>
Reginald
  • 43
  • 1
  • 8
  • Try looking for `WHERE IN()` clause for your SQL query – Qarib Haider Jan 18 '15 at 14:08
  • 1
    possible duplicate of [PHP Multiple Checkbox Array](http://stackoverflow.com/questions/14026361/php-multiple-checkbox-array) – Gerald Schneider Jan 18 '15 at 14:09
  • 1
    For multiple inputs with one name input's `name` attribute should be `name="permit[]"` – u_mulder Jan 18 '15 at 14:09
  • The reason for what @u_mulder correctly points out simply is: you cannot have multiple variables using the same name, that is obvious. You tried exactly that, take a look at the `name` attribute of your checkboxes. His recommendation turns the variable into an array from the point of view php takes. That is why it works. – arkascha Jan 18 '15 at 14:11
  • i've already tried this code, but nothing happened. do i need to put implode function in my query ? `Locational Clearance PALC DP AP` @u_mulder – Reginald Jan 18 '15 at 14:19
  • yes you need to implode the permit values before adding it in IN condition – Bhavya Shaktawat Jan 18 '15 at 14:25
  • i've already updated my code but it returns an error Warning: implode() [function.implode]: Invalid arguments passed in C:\xampp\htdocs\cpdo_ci\application\views\generate.php on line 12 2000 – Reginald Jan 18 '15 at 14:38
  • before implode you have to check it by isset function. cause if your user didn't select any checkbox your form will not pass that variable – Shahadat Hossain Khan Jan 18 '15 at 16:04

2 Answers2

0

i tried this in mySQL Workbench and it works fine

   <?php
    $servername = "localhost";
    $username = "root";
    $password = "";



    $year = $_POST['year'];
    $permit = $_POST['permit'];
    $range_to = $_POST['range_to'];
    $range_from = $_POST['range_from'];
    $permitArray = implode('","', (array)$permit);
    // Create connection
    $conn = mysql_connect($servername, $username, $password);
    // Check connection
    if(! $conn )
{
  die('Could not connect: ' . mysql_error());
}
$sql = "SELECT  permit_type, count(id) as 'no',DATE_FORMAT(date,'%M %Y') as 'month', sum(total_amount) as 'amount'     
        FROM payments
        WHERE permit_type IN ('$permitArray') AND date like '%$year%'
        group by permit_type, DATE_FORMAT(date,'%M %Y')
        ";
        var_dump($permitArray,$year);

mysql_select_db('cpdo_db');
$result = mysql_query( $sql, $conn );
if(! $result )
{
  die('Could not get data: ' . mysql_error());
}
?>

    <div id="tabs">
            <div id="tabs-1" class="tab-pad">
                <table class="table table-striped table-bordered" border="1" id="locdata" cellspacing="0" width="100%">
                    <thead>
                        <tr>
                        <center><h1><?php echo $year; ?></h1></center>
                            <th>Month</th>
                            <th>No</th>
                            <th>Permit Type</th>
                            <th>Total Amount</th>

                        </tr>
                    </thead>
                    <tbody>
                                                                                                                <?php 


                            while($row = mysql_fetch_array($result,MYSQL_ASSOC)){
                                //Creates a loop to loop through results
                                echo '<tr>';
                                    echo '<td>'.'<input type="text" name="permit-type" style="border:none;" readonly value="'.$row['month'].'"/>'.'</td>';
                                        echo '<td>'.'<input name="total-no" type="text" style="border:none;" readonly value="'.$row['no'].'"/>'.'</td>';
                                        echo '<td>'.'<input name="total-no" type="text" style="border:none;" readonly value="'.$row['permit_type'].'"/>'.'</td>';
                                        echo '<td>'.'<input name="total-amount" type="text" style="border:none;" readonly value="'."P".$row['amount'].".00".'"/>'.'</td>';

                                echo '</tr>';

                        }   
                    ?>               
                    </tbody>
                </table>  
          </div>    
         </div>


<?php
mysql_close($conn);
?>

but where i put in my php code,if i check 1 checkbox it returns a result, but when i check 2 or more checkbox no result returns

Reginald
  • 43
  • 1
  • 8
  • The unescaped `$year` direct from `$_POST` makes my skin crawl. PLEASE read about SQL injection and how very easy it is to avoid by using prepared statements or placeholders. Read anywhere. It's the simplest attack in the world. – Rudie Jan 19 '15 at 12:02
-1

Missing part of your code where you passing values of inputs to $_POST variable (you can pass it to another php via ajax serialize or form with method... etc.), but... if I imagine that you have $permits now as an array of inputs values, than you should convert your $permits array to some comma separated vlaues witch can be used in query then:

$comma_separated_permits = implode(",", $permits);

Now you can use it in your query:

... WHERE .... AND permit_type IN ($comma_separated_permits) ...

I've just tested this little example on db table called 'test' with some rows

$array = array ("PALC","DP","AD");
$tosql = implode("','", $array);
$sql = ("SELECT * FROM `test` WHERE `key` IN ('$tosql')");
$result = $db -> query($sql) -> fetchAll(PDO::FETCH_COLUMN,0);
var_dump ($result); 

It works fine... just watchout when using string instead of integer in IN() clausule. My answer doesn't contain bulding your array form checkboxes since you were asking how to query db

Complete example with html part:

<form action="#" method="post">
  <input type="checkbox" name="checks[]" value="PALC" />PALC
  <input type="checkbox" name="checks[]" value="DP" />DP
  <input type="checkbox" name="checks[]" value="AD" />AD
  <input type="submit" />
</form>

then add php:

if (!empty($_POST['checks'])){
    $array = $_POST['checks'];
    $tosql = implode("','", $array);
    $sql = ("SELECT * FROM `test` WHERE `key` IN ('$tosql')");
    $result = $db -> query($sql) -> fetchAll(PDO::FETCH_COLUMN,0);
var_dump ($result);
}
PepeLopez
  • 49
  • 4
  • i tried it but there's an error Warning: implode() [function.implode]: Invalid arguments passed in C:\xampp\htdocs\cpdo_ci\application\views\generate.php on line 12 – Reginald Jan 18 '15 at 14:33
  • Please don't forget to quote and escape those values into SQL! – Rudie Jan 18 '15 at 14:39
  • i always put quote on values in my query @Rudie – Reginald Jan 18 '15 at 14:45
  • As I said I dont know how you pass your input checboxes values, just imagine that your $permits is an array f.e. array of chosen checkboxes ("PALC","DP", "AP"), then IN() query clausule with previous imploded function to array should work... if you got Invalids argument passed error, var_dump your $permits if it is correct array of inputs checkboxes values... if not, you should rework passing inputs values to $permits variable. – PepeLopez Jan 18 '15 at 15:03
  • ...cause you can serialize input values with ajax f.e., thats why I just imagine youve got $permit as an array of checbox values – PepeLopez Jan 18 '15 at 15:13
  • i tried to var_dump($permit); and its working it echo the array of $permit already, now the error in is my sql query, i used WHERE IN ('$permit'), if i select 1 checkbox only it will return a result, but if 2 or more checkbox is selected it has no result @PepeLopez – Reginald Jan 18 '15 at 15:25
  • I've tested some example since you said you got error when you query more than one element of array... example works fine resulted all rows where 'key' is in IN() clausule... – PepeLopez Jan 18 '15 at 18:23
  • @Reginald The escaping part is more important. If `$comma_separated_permits` contains single quotes, your quotes are useless. Insert `') OR 1; --` in there. SQL injection is so easy to avoid. – Rudie Jan 19 '15 at 12:00