限制数据库行插入一个数字?

时间:2014-11-18 08:23:57

标签: php mysql

根据我的代码,我需要将数据的插入限制为3,我的意思是在插入3个数据行之后,它将被限制插入数据。那可能吗?有关更多信息,如借入3次,则无法再插入。反正有没有这样做?我还在学习php,谢谢。

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");
} 

2 个答案:

答案 0 :(得分:1)

您必须先计算用户行数才能进行新插入:

$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');

另外,请检查:Why shouldn't I use mysql_* functions in PHP?

答案 1 :(得分:0)

我不确定我是否理解正确。 您可以使用LIMIT子句限制SELECT查询返回的行数。

确保你要么在其中加上ORDER BY条款,要么确定你不关心哪个&#39;哪个&#39;将插入3行。

见这里: http://dev.mysql.com/doc/refman/5.0/en/select.html