Jump to content

PHP Checkbox ordered by click, send thru post form to a new SQL Query


rodrj

Recommended Posts

I have a code on `page1.php` where I have an array of checkbox populated with mysql data through a query. I can successfully submit the value of the checked checkbox to the `page2.php`. But I want to submit it according to the sequence the checkbox was checked by the user. I´ve tried some javascript, but i´m not familiar to it.
 
My intention is to show on `page2.php` what the user selected, on a specific order, from the `page1.php` form
 
Any help will be appreciated.
 
Thanks
 
Here is my clean code.
 
**page1.php**
    <?php
    $query = "SELECT * FROM imoveis";
    $result = mysql_query($query,$conn);
    ?>
    
    <form action="page2.php" method="post">
    
    <input type="submit" value="Create" id="enviarButton"/></td>
    
    <br><br>
    
    <table border="1">
        <?
        $i = 0;
        
        echo "<tr>";
        
             while($imovel = mysql_fetch_array($result)){
        
         $name = $imovel['empreendimento'];
         $id = $imovel['id'];
     
    ?> 
    
     <td>
     <?=$name;?><br>
     <input type="checkbox" name="op_imovel[]" value="<?=$id;?>">
            </td>
    <?
               $i++;
               if(($i % 3) == 0){
                      echo "</tr><tr>";
                      }
               }
    
    mysql_close();
    
    ?>
    
    </table>
    </form>
 
 
**page2.php**
    <?php
      $checkbox = $_POST['op_imovel'];
      
      if (is_array($checkbox) && count($checkbox) > 0){
     $res = '';
     $tot = count($checkbox) - 1;
     for ($y = 0; $y <= $tot; $y++) {
     
     $res .=$checkbox[$y];
     
     if ($y < $tot)
     $res .= ",";
     }
     
     }
      
      $query = "SELECT * FROM emps WHERE id IN ($res)";
      $result = mysql_query($query,$conn);
    ?>
    
    <br>
    
    
    <div align="center">
    
     <table border="1">
    
    <?
    $i = 0;
    echo "<tr>";
    
     if (is_array($checkbox) && count($checkbox) > 0){
     while($imovel = mysql_fetch_array($result)){ 
     
     $name = ($imovel['emp']);
    ?>
     <td>
     <p>
     <?= $name;?>
     </p>
     
     </td>
    <?
               $i++;
               if(($i % 3) == 0){
                      echo "</tr><tr>";
               }
    
    
     } 
     
     } 
    ?> 
     
    
    </div>
    
    <?  mysql_close(); ?>

 

Link to comment
Share on other sites

Here's an example of my method

 

The javascript increments/decrements a counter variable when a checkbox is checked/unchecked and puts the counter value in the corresponding text field.

 

When processing the form we get the ids that were selected from the checkboxes. This gives our IN (x,y,z) for the selection from the table. This won't affect the order of the selection since IN (x,y,z) gives the same results as IN (z,y,x). To get the right order we specify the order in which we want the id field to be selected using ORDER BY FIELD(id, y,x,z). We get the y,x,z by sorting on the $_GET['seq'] values.

<?php

$mysqli = new mysqli(HOST,USERNAME,PASSWORD,'test');

            /** my data *******************************************
                        CREATE TABLE candidate (
                        id int not null auto_increment primary key,
                        name varchar(40)
                        );

                        INSERT INTO  candidate (name) VALUES
                        ('Anne Adamson'),
                        ('Ben Brown'),
                        ('Charles Cummins'),
                        ('David Dent'),
                        ('Emma Ellis'),
                        ('Fiona Fleming'),
                        ('George Glover'),
                        ('Henry Horner'),
                        ('Ian Illingworth'),
                        ('Jane Jenkins');
            *******************************************************/

//
// process the voting form
//
$results = '';
if (isset($_GET['candidate'])) {
    $list = join(',', $_GET['candidate']);    // selected candidates' ids
    // find the order they were selected
    $seqarray=[];
    foreach ($_GET['seq'] as $id => $seq) {
        if ($seq) {
            $seqarray[$seq] = $id;
        }
    }
    ksort($seqarray);                         // sort ids into correct sequence
    $seqlist = join(',', $seqarray);
    
    // get the candidates in the required order
    $sql = "SELECT  name
            FROM candidate
            WHERE id IN ($list)
            ORDER BY FIELD(id,$seqlist)";
            
    $results = "You voted for<ol>";
    $res = $mysqli->query($sql);
    while ($row = $res->fetch_row()) {
        $results .= "<li>$row[0]</li>";
    }
    $results .= "</ol></hr>\n";
}

            
//
// create the voting input form
//
$sql = "SELECT id
         , name
        FROM candidate
        ORDER BY id ";
$res = $mysqli->query($sql);
$clist = "<table>\n";
while (list($id, $name) = $res->fetch_row()) {
    $clist .= "<tr>
                <td>$name</td>
                <td><input type='checkbox' name='candidate[]' value='$id'   class='candidate'>
                <td><input type='text' name='seq[$id]' id='seq$id' size='2'  class='seq' readonly>
                <tr>\n";
}
$clist .= "</table>\n";
?>
<!DOCTYPE html>
<html>
<head>
<title>Voting Form</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type='text/javascript'>
var counter = 0;
$().ready(function() {
    $("#btnReset").click(function(){counter=0;})
    
    $(".candidate").click(function() {
        var id = $(this).val();
        if (this.checked) {
            if (counter < 3) {
                ++counter;
                $("#seq"+id).val(counter);
            } 
            else {
                this.checked = false;
            }
        }
        else {
            --counter;
            $("#seq"+id).val('');
        }
    })
})
</script>
</head>
<body>
<?=$results?>
<form>
<h3>Select 3 candidates in order of preference</h3>
<?=$clist?>
<input type='submit' name='btnSubmit' value='Vote'>
<input type='reset' name='btnReset' id='btnReset' value='Reset'>
</form>
</body>
</html>

post-3105-0-66801000-1440263506_thumb.png

  • Like 1
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.