PHP - 仅允许对页面

时间:2016-01-17 09:13:15

标签: php html database

我正在尝试为管理员注册创建一个表单。代码正常工作,但多个管理员可以注册此页面。我怎样才能让只有一个管理员注册?

<html >
<head>
<title></title>
</head>
<body>
<?php
print ("<form action='admin.php' method='post'>
    <p>Name
        <input type='text' name='firstname'  />
    </p>
    <p>Surname
        <input type='text' name='lastname' />
    </p>
    <p>Username
        <input type='text' name='username' />
    </p>
    <p>Password
        <input type='password' name='password' />
        </p>
        <p>Email <input type='text' name='email'/>  </p>
      

      
    
  <input type='submit'  value='Register'/>  
</form>

        ");



if( !($database=mysql_connect("localhost","root",""))||!(mysql_select_db("st_login",$database))  )
   print("Could not connect");

if(isset($_POST['firstname'] )&&isset($_POST['lastname'])&&isset($_POST['username'])&&isset($_POST['password'])
  /*&&isset($_POST['notat'])&&isset($_POST['lendet'])*/&&isset($_POST['email'])){
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$username=$_POST['username'];
$password=md5($_POST['password']);
$email=$_POST['email'];
/*
$notat=$_POST['notat'];
$lendet=$_POST['lendet'];
*/

$query = "INSERT INTO  login (firstname, lastname, username,password,email,admin) VALUES ('$firstname', '$lastname',
 '$username','$password','$email',1)";
}
if ( !empty($firstname)&&!empty($lastname)&&!empty($username) &&!empty($password)&&!empty($email))
{
  if(!($result=mysql_query($query,$database)))
{
    print("Could not execute query");
    die (mysql_error());//ose error
}
echo "YOU HAVE BEEN REGISTERED SUCCESSFULLY!You are the admin of this page";

}
else echo 'Fill in all the blank fields';
mysql_close($database);
?>

</body>
</html>
这是我的数据库database

1 个答案:

答案 0 :(得分:1)

在向表单输入用户数据时添加一项检查。检查字段管理员设置为1(或您使用的任何内容)是否存在任何行 该示例代码

$result = mysql_query("SELECT firstname FROM mytable WHERE admin=1");
if(mysql_num_rows($result)== 0) {
     //check if the post variables are set and input the values to the table
} else {
     // Admin already exist      
}

正如评论中所述,您应该停止使用mysql_,并将mysqli_或PDO与预备语句一起使用,下面给出一个示例。请记住,您不能混用API,因此您的整个代码必须从一个代码转换为另一个代码。

$mysqli = new mysqli("host", "user", "password", "database");

$result = $mysqli->query("SELECT firstname FROM mytable WHERE admin=1");
if ($result->num_rows == 0) 
     //check if the post variables are set and input the values to the table
} else {
     // Admin already exist      
}

参考