如何限制进入mysql数据库的行数


How to limit the number of rows entered into mysql database

我有一个表单,让用户存储他们所工作的工作(信用)到mysql数据库。然后,这些信用将在页面上显示出来,供其他用户查看。如何将每个用户可以提交给数据库的积分的数量限制为10?这是我可以用javascript做的吗?

这是我的表格:

 <form action="process.php" form="credits" method="GET"
              enctype="multipart/form-data" name="my_form" id="">
                            <input name="production" type="text" id="production" placeholder="Production" value = "" required>
                            <input name="channel" type="text" id="channel" placeholder="Channel" value = "">
                            <input name="company" type="text" placeholder="Production Company" value = "">
                            <input type="hidden" name="username" value="<?php echo $username; ?>">

  <button name="submit" id ="submit">
                          Submit
                        </button>
</form>

这是它在数据库中的存储方式。

<?php
//Database Connection
include_once "$conx.php";
if( isset($_GET['submit'] )){
$production = $_GET['production'];
$channel = $_GET['channel'];
$company = $_GET['company'];
$username = $_GET['username'];
//updating database
$stmt = $db_conx->prepare('INSERT INTO credits SET production =?, channel =?, company =?, username =?');
$stmt->bind_param('ssss',$production,$channel,$company,$username);
$stmt->execute();
mysqli_close($conx);
//Redirect back
    header("location:credits.php");
}
?>

这样做的最好方法是同时做客户端和服务器端验证,这意味着你应该检查他们是否能够在前端使用javascript提交另一个信用,然后在后端使用PHP进行双重检查。

但是从它的外观来看,每次用户输入新的信用时,您都在刷新整个页面。如果是这种情况,您甚至不需要javascript。你可以为你的表单做这样的事情:

<?php
if ($credits >= 10) {
  echo 'You have reached the maximum amount of credits allowed.';
}
else {
  echo [FORM GOES HERE];
}
?>

其他观察:你写代码的方式似乎很容易被破解。例如,如果我是用户"joe",我可以很容易地为用户"innocent_jane"提交内容,只需在提交之前编辑页面上的隐藏字段。使用隐藏字段的更好方法可能是在用户登录后将用户名存储在会话变量中。

您可能想要这样做:

$check = $db_conx->query("SELECT COUNT(*) FROM credits WHERE username=?");
$check->bind_param("s", $username);
$check->execute();
if ($check->fetch_row()[0] >= 10) {
    // show the user an error page
} else {
    // proceed with the insert query
}

这是仓促编写的伪代码,因此您可能需要对其进行调整以使其实际工作,但希望这传达了您想要使用的一般方法。

您可以先检查数据库中的用户名:

if($result = $db_conx->query("SELECT * FROM credits WHERE username == ".$username))
{
    if(($result->num_rows) < 10){ // Less than 10 credits for that username
    // do the database updating
    }
    $result->close();
} else { // It didn't find any entries for that username
// do the database updating