繁体   English   中英

如何限制进入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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM