<?php
$connection=mysqli_connect("host", "username", "password", "database");
$sql="SELECT COUNT(*) from database_users";
$stmt = $connection->prepare($sql);
$stmt->execute();
$res = $stmt->get_result();
$users = $res->fetch_array(MYSQLI_ASSOC);
if ($users['COUNT(*)'] < 4) {
?>
// html goes here, outside of the php tags
<?php
} else {
echo "Sorry, you have reached the user account limit.";
};
?>
Code to limit user registration - hide/show form php [closed]
-
15-10-2022 - |
문제
I've just started to learn PHP - Not very good. I have created a form (see below) which I would like people to sign up to but I would like to limit this to a certain number of members. For example 4 users can sign up when it reaches that amount it will hide the form and display a message saying "sorry, you have reached the user account limit."
<form action="users.php?new=1" method="post">
<input type="hidden" name="action" value="newUser"/>
<input type="hidden" name="id" value="0"/>
<fieldset>
<legend>Add new user</legend>
<?php if(isset($msg)) { echo $msg;}?>
<p>
<label>Full name: </label>
<input name="name" value="<?php if(isset($name)) { echo $name;}?>" style="width:400px;"/>
</p>
<p>
<label>Email: </label>
<input name="email" value="<?php if(isset($email)) { echo $email;}?>" style="width:400px;"/>
</p>
<p>
<label>Password: </label>
<input name="password" type="password" value="" style="width:400px;"/>
</p>
<p>
<label>Phone number: </label>
<input name="phone" value="<?php if(isset($phone)) { echo $phone;}?>" style="width:400px;"/>
</p>
<p>
<label>User level:</label>
<select name="access" class="dropdown">
<option value="no" <?php if(isset($access)) { if ($access =='no'){ echo ' selected="selected" ';}}?>>User</option>
<option value="yes" <?php if(isset($access)) { if ($access =='yes'){ echo ' selected="selected" ';}}?>>Admin</option>
</select>
Note: Admin users will have full access to all areas.
Please can someone help me! Code would be lovely!
Thanks, Charlie
해결책
다른 팁
Using whatever database method you're using, you should take a look into the database and see how many results are returned. If there are 4 or more, then don't display the form, if not, then display it.
Seeing as you're new to PHP, the chances of your database language will be mysql_*
, which is not very good, but unfortunately it's widespread across the internet.
Please look into PDO
or mysqli_*
if you haven't already.
If you're using mysqli:
<?php
$con=mysqli_connect("host", "username", "password", "database");
if (mysqli_connect_errno($con))
{
echo "Failed to connect: " . mysqli_connect_error();
}
$sql= "SELECT * FROM table";
if ($result=mysqli_query($con,$sql){
$rowcount = mysqli_num_rows($result);
}
Then you can use $rowcount
in an if
to see if it is more than 4.
eg.
if ($rowcount > 4){
echo "Sorry, no more users can sign up";
}else{
//form here
}