How can i limit inserts to just 3 rows for each category in table? I am working with php and pdo. I have some categories and each category must have max 3 subcategories. Everything is stored in db, tables look like this.
To make it clear! I have some categories in menu and each of those category can have maximum of 3 subcategories. Of course not with the same name, but it can't be more then 3 in each category. I have input for one at the time, that means you can insert more then one at the time, but it can't be more then 3 in db.
Some category
- some subcategory
- some subcategory
- some subcategory
category
id | category |
subcategory
id | subcategory_name | id_category |
For now, my code looks like this.
if(isset($_POST['sub'])) {
$InputSubcategory = $_POST['InputSubcategory'];
$InputId = $_POST['InputId'];
$sql = $pdo->prepare("INSERT INTO subcategory(subcategory_name,id_category)
VALUES(:field1,:field2)");
$sql->execute(array(':field1' => $InputSubcategory,
':field2' => $InputId));
$affected_rows = $sql->rowCount();
if ($affected_rows > 0) {
header( "refresh:0" );
die();
}
}
if(isset($_POST['cat'])) {
$InputCategory = $_POST['InputCategory'];
$sql = $pdo->prepare("INSERT INTO category(category)
VALUES(:field1)");
$sql->execute(array(':field1' => $InputCategory));
$affected_rows = $sql->rowCount();
if ($affected_rows > 0) {
header( "refresh:0" );
die();
}
}
EDIT:
I made it work! What i did is next. Count()
rows in each table, then in if compare whether the counted number greater than or equal to 3. If if
is true show error if false continue to insert.
if(isset($_POST['cat'])) {
$nRows = $pdo->query('select count(*) from category')->fetchColumn();
if ($nRows >= 3) {
echo'
<div class="alert alert-warning">
<span class="glyphicon glyphicon-ok"></span> <strong>Warning</strong>
<hr class="message-inner-separator">
<p>You reach maximum category limit.</p>
</div>';
header( "refresh:2;url=insert.php" );
} else {
$InputCategory = $_POST['InputCategory'];
$sql = $pdo->prepare("INSERT INTO category(category)
VALUES(:field1)");
$sql->execute(array(':field1' => $InputCategory));
$affected_rows = $sql->rowCount();
if ($affected_rows > 0) {
header( "refresh:0" );
die();
}
}
}