I have a form where users can enter product id and its quantity. What I am trying to acheive is when the user submits the form, in the controller I want to check in database to see if the provided product’s quantity is available in stock, if not I want to display a validation error message in the form. If everything is okay I want to proceed to the next step.
Could you please show me how my controller should look like if I want to achieve this using Codeigniter’s default validation library?
This is my db table name: product
product_id category_id product_name product_price product_stock
1 1 Mango Juice 25 100
2 2 Pepsi 10 0
This is my View File — My Form (check this link to see the form)
<form name="form" action="base_url/my_controller/function" method="post">
<label>One</label>
Product ID:<input type="text" name="productid[]" value="">
Product Quantity: <input type="text" name="quantity[]" value=""> <br>
<label>Two</label>
Product ID:<input type="text" name="productid[]" value="">
Product Quantity: <input type="text" name="quantity[]" value=""> <br>
<!-- there may be more inputs like above (users can create new inputs
as many as they want) // I have a jquery function to create new rows-->
<input type="submit" value="submit">
</form>
Edited Part New
function test(){
$productid = ($_POST['productid']);
$quantity = ($_POST['quantity']);
for($i = 0; $i < count($productid); $i++){
$result=$this->enquiry($productid[$i],$quantity[$i]);
}
/* Now I am stuck here. I don't understand how to find out if the
products are available or not. If not I want to show the
error message in the form :( */
}//function ends
function enquiry($productid,$quantity){
$query = $this->db->query("SELECT product_stock FROM products
WHERE product_id=$productid");
if ($query->num_rows() > 0){
foreach ($query->result() as $row){
$product_stock=$row->product_stock;
}
}
if($product_stock>$quantity) { return FALSE; }
else { return TRUE; }
}//function Ends
You can use a callback function. read here
is_available_in_stockwill check in the database the available quantity. It is recommended to check it using a model.EDIT:
I would advise against using the form validation like mentioned above for this type of validation because you have two arrays which need to match based on their index. When using the callback function you do not know which product’s quantity you are working with.
My recommendation:
Using this code, the
is_available_in_stockfunction you wrote should work.Second EDIT: