lye yan nian
lye yan nian

Reputation: 143

restrict database row insert by a number?

Based on my codes, i need to restrict the insertion of the data by 3, i mean is like after the insertion of 3 data row, it will be restricted from inserting in data. Is that possible? For more information, is like the borrow inserting 3 times, then it cannot be inserted anymore. Is there anyway to do so? I am still learning php by the way, thank you.

if(isset($_POST['selector']))
$id=$_POST['selector'];
else
$id = '';
$member_id  = $_POST['member_id'];
$due_date  = $_POST['due_date'];
$isbn  = $_POST['due_date'];

if ($id == '' ){
//header("location: borrow.php");
if(isset($_POST['isbn'])){
    $isbn = $_POST['isbn'];
    $query = mysql_query("select book_id from book WHERE isbn = '$isbn'")or die(mysql_error());
    $count = mysql_num_rows($query);
        if($count > 0){
            $row = mysql_fetch_array($query);
            $bookid = $row['book_id'];
            $date =  date('Y-m-d');
        }
    mysql_query("insert into borrow (member_id,book_id,date_borrow,due_date) values         ('$member_id','$bookid','$date','$due_date')")or die(mysql_error());     
}
else{
  header("location: borrow.php");
}
}else{
mysql_query("insert into borrow (member_id,date_borrow,due_date) values ('$member_id',NOW(),'$due_date')")or die(mysql_error());
$query = mysql_query("select * from borrow order by borrow_id DESC")or die(mysql_error());
$row = mysql_fetch_array($query);
$borrow_id  = $row['borrow_id'];
}else{
mysql_query("insert into borrow (member_id,date_borrow,due_date) values ('$member_id',NOW(),'$due_date')")or die(mysql_error());
$query = mysql_query("select * from borrow order by borrow_id DESC")or die(mysql_error());
$row = mysql_fetch_array($query);
$borrow_id  = $row['borrow_id'];
$N = count($id);
for($i=0; $i < $N; $i++)
{
mysql_query("insert borrowdetails (book_id,borrow_id,borrow_status)             
values('$id[$i]','$borrow_id','pending')")or die(mysql_error());
}
header("location: borrow.php");
} 

Upvotes: 0

Views: 89

Answers (2)

fdehanne
fdehanne

Reputation: 1717

You just have to count number of user row before to make a new insert :

$query = mysql_query("SELECT COUNT(*) AS count FROM borrow WHERE member_id = '".$member_id."'");
$row = mysql_fetch_assoc($query);

if ( $row['count'] >= 3 )
    echo('Max insert');

Also, check this : Why shouldn't I use mysql_* functions in PHP?

Upvotes: 1

Persixty
Persixty

Reputation: 8589

I'm not sure I understand you correctly. You can restrict the number of rows returned by SELECT query using the LIMIT clause.

Make sure you either put an ORDER BY clause in there or determine that you don't care 'which' 3 rows will get inserted.

See here: http://dev.mysql.com/doc/refman/5.0/en/select.html

Upvotes: 0

Related Questions