mercredi 7 juin 2017

How to check if corresponding checkbox's quantity array value is set?

I'm trying to make a shopping page. I've kept checkboxes for selection and a number type field for quantity. As checkboxes are array I took the quantity field also an array... I know that we can check the checkbox state with checked method, now what I'm trying to achieve is to fetch corresponding quantity value and store it in a session varaible.

<?php
session_start();
if(isset($_POST['sub'])){
    $_SESSION['cbb']=$_POST['cb'];
    if(isset($_POST['qnty'])){
    $_SESSION['qtty']=$_POST['qnty'];
    header("location:userlogin.php");
    }
}
?>
<html>
<head>
</head>
<body topmargin="20">
<font color='#7FFF00'>
 <h1 align='center'>ONLINE SHOPPING</h1>
</font>
<form name="onshop" align="right" action="<?=$_SERVER["PHP_SELF"]?>" 
method="post" onsubmit="return validate()">
<input type="submit" value="Add to cart" name="sub" style="background-
color:#7FFF00" />
<input type="reset" value="Reset" style="background-color:#7FFF00"/>
<?php
$db=mysqli_connect("localhost","root","","onlineshop");
if(!$db){
    echo "Connection failure.";
}
$sql="SELECT * FROM stock";
$result=mysqli_query($db,$sql)or die("Invalid query ".mysqli_error($db));
echo "<TABLE width=50% height=70% align='center'>";
echo "<TR><TH>ITEM NAME</TH><TH>PRICE</TH><TH>IMAGE</TH><TH>Do you like?
</TH><TH>QUANTITY</TH></TR>";
while($myrow=mysqli_fetch_array($result))
    {
        echo "<TR><TD align='center'>";
        echo $myrow["item"];
        echo "</TD>";
        echo "<TD align='center'>";
        echo $myrow["price"];
        echo "</TD>";
        echo "<TD align='center'>";
        $image=$myrow["image"];
        echo '<img height="100" width="100" src="data:image/jpeg;base64,'.base64_encode( $image ).'"/>';
        echo "</TD>";
        echo "<TD align='center'>";
        $itm_id=$myrow["id"];
        echo "<input type='checkbox' name='cb[]' value='$itm_id'>";
        echo "</TD>";
        echo "<TD align='center'>";
        echo "<input type='number' name='qnty[]' value='1' max='50' 
min='1'>";
        echo "</TD>";
        echo "</TR>";
    }   
echo "</TABLE>";

mysqli_close($db);  

?>

</form>

<script type="text/JavaScript">
function validate(){
    var count=0;
    var i;
    var cbelements = document.getElementsByName("cb[]");

    if(count==0){
        for(i=0;i<cbelements.length;i++){
            if(cbelements[i].checked){
                count++;
            }
        }
        if(count<1){
            alert("Select atleast 1 item.");
            return false;
        }
    }
}
</script>
</body>
</html>

Can the onchange event be useful in anyway? or the associative array ?




Aucun commentaire:

Enregistrer un commentaire