Home > database >  Want to limit the insert query with respective column name's value according to the row count
Want to limit the insert query with respective column name's value according to the row count

Time:05-25

I want to limit the insert query with respective column name's value according to the row count. What I want to do is, there are 5 areas and each area accept only 4 values and It will insert into database. If I add more values into the same area, it has to show alert "Maximum is 4."

if ($chk=='issue'){
    $sql="SELECT count(*) 
            from access_request.tbl_sealcable 
            where seal_area='.$seal_area'";
    $result= mysqli_query($conn,$sql);
    if (mysqli_num_rows($result) < 5){
        $barcodeArray = explode(",",$seal_barcode);
        foreach($barcodeArray as $value){
            $seal_barcode = $value;
            $sql1 = "INSERT INTO access_request.tbl_sealcable 
                            (seal_barcode, seal_area, dt_issue, 
                            issue_admin, receive_by, receive_id) 
                    VALUES ('$seal_barcode', '$seal_area', now(), 
                            '$admin_name', '$receive_by', '$receive_id')";
            $result1 = mysqli_query($conn,$sql1);
    }
} else {
    echo '<script language="javascript">';
    echo 'alert("Limit exceeded.")';
    echo '</script>';
}

CodePudding user response:

A COUNT() query will return 1 Row ALWAYS, even if the count is Zero, you are testing the number of rows returned in this line

if (mysqli_num_rows($result) < 5){

Of course that wont work, you need to get the count from the resultset, so

  1. Change the query to do COUNT(*) as cnt then you can access the result column more easily

  2. Fetch the resultset and test the value of cnt

$row = $result->fetch_assoc();
if ($row['cnt'] >= 4) {

    . . .
}

BIG NOTE

Your script is open to SQL Injection Attack. Even if you are escaping inputs, its not safe! You should always use prepared parameterized statements in either the MYSQLI_ or PDO API's instead of concatenating user provided values into the query. Never trust ANY user input!

  • Related