简体   繁体   中英

PHP/MySQL - checkboxes of data from db, submission of 2 parametres

So, i'm struggling with that for a long time.

I need to make a list with checkboxes from DB like [checkbox of car id and value][brand][model]. Then, we need to choose two cars from list, and two cars are chosen - we should block all unchecked till checked won't be unchecked. Then, we need to sumbit into list.php page two car id of chosen cars. And submission won't be done if one or no car are chosen.

I don get it how to realise. Anybody knows how to solve this? And yes: jquery is desirable, ajax is not ('cos i never worked with that and i don't think i need it here because i need just to transmit parametres to another page)

My code

<?php
$hostname = "localhost";
$username = "root";
$password = "";
$dbname = "jdmdb";

$con = mysqli_connect($hostname, $username, $password) or die(mysqli_error());
$con->query("SET NAMES cp1251");
$con->select_db($dbname);
$result = mysqli_query($con, 'select * from cars') or die(mysqli_error($con));
$rows = $result->fetch_all(MYSQLI_ASSOC);
?>

<html>
    <head>
            <meta http-equiv="Content-Tуpe" сontent="tехt/html; charset=utf-8">
        <title>JDM Database</title>
        <script src=../js/jquery-2.1.4.js type=text/javascript></script>
    </head>
    <body>
        <form name=carlist method=post action="list.php">
        <?
            foreach ($rows as $row) {
                echo '<input type=checkbox name="car_short" value="'.$row['car_short'].' id='.$row['car_short'].'"> '.$row['brand'].' '.$row['model'].' '.$row['spec'].' ('.$row['year'].')<br/>';
            }
            $res = count($rows);  
            echo '<input type=submit value=123>';
        ?>
        </form>
<?            
        mysqli_close($con);
    ?>
    </body>
</html>

You can send array of data to list.php For that you should use following syntax

echo '<input type=checkbox name="car_short[]" value="'.$row['car_short'].' id='.$row['car_short'].'"> '.$row['brand'].' '.$row['model'].' '.$row['spec'].' ('.$row['year'].')<br/>';

This will send send $_POST['car_short'] as array of two selected values. And if you want to check number of selected cars after submission then use

if(count($_POST['car_short'])<2){// place error;}

Else you can use jquery to check how many checkboxes are selected else return false. For that change the form code like this

<form method=post action="list.php" onSubmit="check();">

and check function will be

function check(){
   var n = $("input:checkbox:checked").length;
   return n>1;
}

Note: Please note the method the exact code may not work properly since i misspelled variables

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