如何使用php将有限记录插入mysql

时间:2014-01-03 06:55:51

标签: php

有没有办法注册有限的用户。意味着我使用insert Query注册了10个用户。现在我想检查数据库中是否有10个用户注册。停止注册更多用户。并显示消息抱歉,我们无法创建您已注册的10位用户。

<?php
require('connection.php');
    if($_SERVER['REQUEST_METHOD']=='POST')
    {

            $user_name = $_POST['username'];
            $father_name = $_POST['fname'];
            $password = $_POST['password'];
            $confirm_password = $_POST['confirmpassword'];
            if($password==$confirm_password){
            $insert = mysql_query("insert into user values('','$user_name','$father_name','$password','$confirm_password')");
            }
            else
            {
                $passwordmsg = "Password Must Be Matched";
            }
            if($insert)
            {
                $msg = "Registration Succesfull";   
            }
            else
            {
                $msg = "Registration failled please Try Again Later !";
            }

    }
?>

3 个答案:

答案 0 :(得分:0)

在插入新用户之前,请使用select命令检查用户数并返回行数。如果行数大于10,则显示您的消息。 一个简单的if条件可以解决你的问题。

<?php
 require('connection.php');
 if($_SERVER['REQUEST_METHOD']=='POST')
  {
    $no_of_rows = mysql_query("count(*) FROM user");

    if($no_of_rows <10){
    $user_name = $_POST['username'];
    $father_name = $_POST['fname'];
    $password = $_POST['password'];
    $confirm_password = $_POST['confirmpassword'];
    if($password==$confirm_password){
    $insert = mysql_query("insert into user          values('','$user_name','$father_name','$password','$confirm_password')");
    }
    else
    {
        $passwordmsg = "Password Must Be Matched";
    }
    if($insert)
    {
        $msg = "Registration Succesfull";   
    }
    else
    {
        $msg = "Registration failled please Try Again Later !";
    }
  }
  else{
    $msg = "Number of users reached limit. Please try again later!"
   }
 }
?>

答案 1 :(得分:0)

$mysqli = new mysqli($host,$user, $password, $database);
$sql = "SELECT * FROM table";
$result = $mysqli->query($sql) or trigger_error($mysqli->error." [$sql]"); 
if($result->num_rows == 10) {
   //no more users can be registered
} else {
   //insert and register new user
}
$mysqli->close() ;

浏览文档here

答案 2 :(得分:0)

require('connection.php');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $str_sql = mysql_query("SELECT * FROM user");
    $int_rows = mysql_num_rows($str_sql);
    if ($int_rows < 10) {
        $user_name = $_POST['username'];
        $father_name = $_POST['fname'];
        $password = $_POST['password'];
        $confirm_password = $_POST['confirmpassword'];
        if ($password == $confirm_password) {
            $insert = mysql_query("insert into user values('','$user_name','$father_name','$password','$confirm_password')");
        } else {
            $passwordmsg = "Password Must Be Matched";
        }
        if ($insert) {
            $msg = "Registration Succesfull";
        } else {
            $msg = "Registration failled please Try Again Later !";
        }

    }
}