2015-05-21 69 views
0

我已經在php中創建了一個註冊頁面,我已經爲新用戶註冊進行了驗證。問題是這些值沒有被插入到MySql數據庫中。我想要將數據插入MySql.One更多的問題是,點擊提交數據字段應該是空的。 請幫忙!將表單值提交到MySql

<?php session_start(); ?> 
<html> 
<head><title>MRA</title> 
<style> 
#heading{ text-align:right;font-size: 25px;float:right;margin:50px 20px;} 
a:hover{ color:#BEBEBC; } 
a{ color:black;} 
#img{margin:10px 10px;} 
</style> 
</head> 
<body background="a9.jpg"> 
<img id="img" src="HITECHLOGO.jpg" width="150px" height="100px"> 
<h1 align="center" style="position:absolute;top:30px; left:450px;">USER REGISTRATION</h1> 
<div id="heading"> 
<a href="adminhomepage.php" style="text-decoration:none;">Home</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
<?php echo ucwords($_SESSION['usr_name']); ?></font>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
<a href="registration.php" style="text-decoration:none;">Add User</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
<a href="logout.php" style="text-decoration:none;">Logout</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
<a href="UserManual.pdf" target="_blank" style="text-decoration:none;">Help</a></div> 
<hr width="100%"> 
<script type="text/javascript"> 
     var specialKeys = new Array(); 
     specialKeys.push(8); //Backspace 
     function IsNumeric(e) { 
      var keyCode = e.which ? e.which : e.keyCode 
      var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1); 
      document.getElementById("error").style.display = ret ? "none" : "inline"; 
      return ret; 
      } 
</script> 
    <?php 
    // define variables and set to empty values 
    $nameErr = $emailErr = $genderErr = $mobErr = $uidErr = $pwdErr =$roleErr= ""; 
    $txtname = $gender = $txtmob = $txteid = $txtuid = $txtpwd = $role= ""; 
    if ($_SERVER["REQUEST_METHOD"] == "POST") 
     { 
      if (empty($_POST["txtname"])) 
       { 
        $nameErr = "Name is required"; 
       } else 
       { 
        $txtname = test_input($_POST["txtname"]); 
        // check if name only contains letters and whitespace 
        if (!preg_match("/^[a-zA-Z ]*$/",$txtname)) { 
         $nameErr = "Only letters and white space allowed"; 
        } 
       } 
      if (empty($_POST["txteid"])) 
       { 
        $emailErr = "Email is required"; 
       } else 
       { 
        $txteid = test_input($_POST["txteid"]); 
        // check if e-mail address is well-formed 
        if (!filter_var($txteid, FILTER_VALIDATE_EMAIL)) 
         { 
          $emailErr = "Invalid email format"; 
         } 
       } 
      if (empty($_POST["gender"])) 
       { 
        $genderErr = "Gender is required"; 
       } else 
       { 
        $gender = test_input($_POST["gender"]); 
       } 
      if (empty($_POST["txtmob"])) 
       { 
        $mobErr = "Mobile No. is required"; 
       } else 
       { 
        $txtmob = test_input($_POST["txtmob"]); 
        //check only numbers are given 
        if(preg_match("/^d{10}$/", $txtmob)) 
         { 
          $mobErr = "Input digits (0 - 9)"; 
         } 
       } 
      if (empty($_POST["txtuid"])) 
       { 
        $uidErr = "User Id is required"; 
       } else 
       { 
        $txtuid = test_input($_POST["txtuid"]); 
       } 
      if (empty($_POST["txtpwd"])) 
       { 
        $pwdErr = "Password is required"; 
       } else 
       { 
        $txtpwd = test_input($_POST["txtpwd"]); 
       } 
      if (empty($_POST["role"])) 
       { 
        $roleErr = "Role is required"; 
       } else 
       { 
        $role = test_input($_POST["role"]); 
       } 
     } 
    else 
     { 
      if (!empty($_POST)) 
       { 
        $host="localhost"; // Host name 
        $username="root"; // Mysql username 
        $password=""; // Mysql password 
        $db_name="testmra"; // Database name 
        // Connect to server and select databse. 
        $conn=mysqli_connect($host,$username,$password) or die("cannot connect"); 
        mysqli_select_db($conn,$db_name); 
        $name = mysqli_real_escape_string($conn, $_POST['txtname']); 
        $gender =$_POST['gender']; 
        $mobile = mysqli_real_escape_string($conn, $_POST['txtmob']); 
        $email = mysqli_real_escape_string($conn, $_POST['txteid']); 
        $username = mysqli_real_escape_string($conn, $_POST['txtuid']); 
        $userpass = mysqli_real_escape_string($conn, $_POST['txtpwd']); 
        $role= $_POST['role']; 
        $res=mysqli_query($conn,"SELECT username FROM newuser WHERE username='$username'"); 
        $row=mysqli_fetch_row($res); 
        if($row>0) 
         { 
          echo '<script language="javascript">'; 
          echo 'alert("Username '.$username.' already been selected")'; 
          echo '</script>'; 
         } 
        else 
         { 
          $sql="INSERT INTO newuser (name,gender,contactno,emailid,username,userpass,role)VALUES('$name','$gender','$mobile','$email','$username','$userpass','$role')"; 
          if (mysqli_query($conn,$sql)) 
           { 
            header("location:registration.php"); 
           } 
          else 
           { 
            die('Error: Cannot connect to db'); 
           } 
         } 
       } 
     } 
    function test_input($data) { 
     $data = trim($data); 
     $data = stripslashes($data); 
     $data = htmlspecialchars($data); 
     return $data; 
    } 
    ?> 
<table align="center" cellpadding="5" cellspacing="5"> 
<tr><td colspan="2" align="left"><font color="red">All fields are mandatory</font></td></tr> 
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 
<tr><td>Full Name &nbsp; : </td><td><input type="text" name="txtname" value="<?php echo $txtname ?>">&nbsp;&nbsp;&nbsp;<font color="red"><?php echo $nameErr; ?></td></tr> 
<tr><td>Gender &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; : </td><td><input type="radio" name="gender" value="Male" checked="checked">Male <input type="radio" name="gender" value="Female">Female&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<font color="red"><?php echo $genderErr;?></td></tr> 
<tr><td>Mobile No. : (+91)</td><td><input name="txtmob" maxlength="10" type="text" id="text1" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" /><span id="error" style="color: Red; display: none"></span>&nbsp;&nbsp;&nbsp;<font color="red"><?php echo $mobErr; ?></td></tr> 
<tr><td>Email Id &nbsp;&nbsp;&nbsp;&nbsp; : </td><td><input type="text" name="txteid" value="<?php echo $txteid ?>">&nbsp;&nbsp;&nbsp;<font color="red"><?php echo $emailErr;?></td></tr> 
<tr><td>User Id &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; : </td><td><input type="text" name="txtuid" value="<?php echo $txtuid ?>">&nbsp;&nbsp;&nbsp;<font color="red"><?php echo $uidErr;?></td></tr> 
<tr><td>Password &nbsp;&nbsp;&nbsp; : </td><td><input type="password" name="txtpwd" value="<?php echo $txtpwd ?>">&nbsp;&nbsp;&nbsp;<font color="red"><?php echo $pwdErr;?></td></tr> 
<tr><td>Role : </td><td><input type="radio" name="role" value="User" 
checked="checked">User<input type="radio" name="role"value="Admin">Admin<font color="red"><?php echo 
$roleErr;?></td></tr> 
<tr><td><input type="submit" value="Submit" name="btnsave"></td></tr> 
</form> 
</tr> 
</table> 
</body>  
</html> 
+5

您應該學會使用準備好的查詢,而不是將變量替換爲查詢。 – Barmar

+0

沒有「數據字段」。提交時哪個字段應該是空的? – Barmar

+0

您是否從INSERT中收到錯誤? – Barmar

回答

0

你不能輸出調用header(),所以你必須要做到這一點底,沒有開始之前的任何HTML。您還應該在header('location:registration.php')之後撥打exit(),因爲重定向時輸出會被忽略。這將解決插入成功時表單未被清除的問題。

我沒有看到INSERT聲明的問題,所以我不能解釋爲什麼它沒有插入。

<?php session_start(); ?> 
    <?php 
    // define variables and set to empty values 
    $nameErr = $emailErr = $genderErr = $mobErr = $uidErr = $pwdErr =$roleErr= ""; 
    $txtname = $gender = $txtmob = $txteid = $txtuid = $txtpwd = $role= ""; 
    if ($_SERVER["REQUEST_METHOD"] == "POST") 
     { 
      if (empty($_POST["txtname"])) 
       { 
        $nameErr = "Name is required"; 
       } else 
       { 
        $txtname = test_input($_POST["txtname"]); 
        // check if name only contains letters and whitespace 
        if (!preg_match("/^[a-zA-Z ]*$/",$txtname)) { 
         $nameErr = "Only letters and white space allowed"; 
        } 
       } 
      if (empty($_POST["txteid"])) 
       { 
        $emailErr = "Email is required"; 
       } else 
       { 
        $txteid = test_input($_POST["txteid"]); 
        // check if e-mail address is well-formed 
        if (!filter_var($txteid, FILTER_VALIDATE_EMAIL)) 
         { 
          $emailErr = "Invalid email format"; 
         } 
       } 
      if (empty($_POST["gender"])) 
       { 
        $genderErr = "Gender is required"; 
       } else 
       { 
        $gender = test_input($_POST["gender"]); 
       } 
      if (empty($_POST["txtmob"])) 
       { 
        $mobErr = "Mobile No. is required"; 
       } else 
       { 
        $txtmob = test_input($_POST["txtmob"]); 
        //check only numbers are given 
        if(preg_match("/^d{10}$/", $txtmob)) 
         { 
          $mobErr = "Input digits (0 - 9)"; 
         } 
       } 
      if (empty($_POST["txtuid"])) 
       { 
        $uidErr = "User Id is required"; 
       } else 
       { 
        $txtuid = test_input($_POST["txtuid"]); 
       } 
      if (empty($_POST["txtpwd"])) 
       { 
        $pwdErr = "Password is required"; 
       } else 
       { 
        $txtpwd = test_input($_POST["txtpwd"]); 
       } 
      if (empty($_POST["role"])) 
       { 
        $roleErr = "Role is required"; 
       } else 
       { 
        $role = test_input($_POST["role"]); 
       } 
     } 
    else 
     { 
      if (!empty($_POST)) 
       { 
        $host="localhost"; // Host name 
        $username="root"; // Mysql username 
        $password=""; // Mysql password 
        $db_name="testmra"; // Database name 
        // Connect to server and select databse. 
        $conn=mysqli_connect($host,$username,$password) or die("cannot connect"); 
        mysqli_select_db($conn,$db_name); 
        $name = mysqli_real_escape_string($conn, $_POST['txtname']); 
        $gender =$_POST['gender']; 
        $mobile = mysqli_real_escape_string($conn, $_POST['txtmob']); 
        $email = mysqli_real_escape_string($conn, $_POST['txteid']); 
        $username = mysqli_real_escape_string($conn, $_POST['txtuid']); 
        $userpass = mysqli_real_escape_string($conn, $_POST['txtpwd']); 
        $role= $_POST['role']; 
        $res=mysqli_query($conn,"SELECT username FROM newuser WHERE username='$username'"); 
        $row=mysqli_fetch_row($res); 
        if($row>0) 
         { 
          echo '<script language="javascript">'; 
          echo 'alert("Username '.$username.' already been selected")'; 
          echo '</script>'; 
         } 
        else 
         { 
          $sql="INSERT INTO newuser (name,gender,contactno,emailid,username,userpass,role)VALUES('$name','$gender','$mobile','$email','$username','$userpass','$role')"; 
          if (mysqli_query($conn,$sql)) 
           { 
            header("location:registration.php"); 
            exit(); 
           } 
          else 
           { 
            die('Error: Cannot connect to db'); 
           } 
         } 
       } 
     } 
    function test_input($data) { 
     $data = trim($data); 
     $data = stripslashes($data); 
     $data = htmlspecialchars($data); 
     return $data; 
    } 
    ?> 
<html> 
<head><title>MRA</title> 
<style> 
#heading{ text-align:right;font-size: 25px;float:right;margin:50px 20px;} 
a:hover{ color:#BEBEBC; } 
a{ color:black;} 
#img{margin:10px 10px;} 
</style> 
</head> 
<body background="a9.jpg"> 
<img id="img" src="HITECHLOGO.jpg" width="150px" height="100px"> 
<h1 align="center" style="position:absolute;top:30px; left:450px;">USER REGISTRATION</h1> 
<div id="heading"> 
<a href="adminhomepage.php" style="text-decoration:none;">Home</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
<?php echo ucwords($_SESSION['usr_name']); ?></font>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
<a href="registration.php" style="text-decoration:none;">Add User</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
<a href="logout.php" style="text-decoration:none;">Logout</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
<a href="UserManual.pdf" target="_blank" style="text-decoration:none;">Help</a></div> 
<hr width="100%"> 
<script type="text/javascript"> 
     var specialKeys = new Array(); 
     specialKeys.push(8); //Backspace 
     function IsNumeric(e) { 
      var keyCode = e.which ? e.which : e.keyCode 
      var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1); 
      document.getElementById("error").style.display = ret ? "none" : "inline"; 
      return ret; 
      } 
</script> 
<table align="center" cellpadding="5" cellspacing="5"> 
<tr><td colspan="2" align="left"><font color="red">All fields are mandatory</font></td></tr> 
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 
<tr><td>Full Name &nbsp; : </td><td><input type="text" name="txtname" value="<?php echo $txtname ?>">&nbsp;&nbsp;&nbsp;<font color="red"><?php echo $nameErr; ?></td></tr> 
<tr><td>Gender &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; : </td><td><input type="radio" name="gender" value="Male" checked="checked">Male <input type="radio" name="gender" value="Female">Female&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<font color="red"><?php echo $genderErr;?></td></tr> 
<tr><td>Mobile No. : (+91)</td><td><input name="txtmob" maxlength="10" type="text" id="text1" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" /><span id="error" style="color: Red; display: none"></span>&nbsp;&nbsp;&nbsp;<font color="red"><?php echo $mobErr; ?></td></tr> 
<tr><td>Email Id &nbsp;&nbsp;&nbsp;&nbsp; : </td><td><input type="text" name="txteid" value="<?php echo $txteid ?>">&nbsp;&nbsp;&nbsp;<font color="red"><?php echo $emailErr;?></td></tr> 
<tr><td>User Id &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; : </td><td><input type="text" name="txtuid" value="<?php echo $txtuid ?>">&nbsp;&nbsp;&nbsp;<font color="red"><?php echo $uidErr;?></td></tr> 
<tr><td>Password &nbsp;&nbsp;&nbsp; : </td><td><input type="password" name="txtpwd" value="<?php echo $txtpwd ?>">&nbsp;&nbsp;&nbsp;<font color="red"><?php echo $pwdErr;?></td></tr> 
<tr><td>Role : </td><td><input type="radio" name="role" value="User" 
checked="checked">User<input type="radio" name="role"value="Admin">Admin<font color="red"><?php echo 
$roleErr;?></td></tr> 
<tr><td><input type="submit" value="Submit" name="btnsave"></td></tr> 
</form> 
</tr> 
</table> 
</body>  
</html> 
+0

先生,這是行不通的。這兩個問題都沒有解決 –

0

首先,您的if語句存在問題,因此您的插入查詢從未達到過。

這是你擁有的一切:

if ($_SERVER["REQUEST_METHOD"] == "POST") 
    { 
     //validation code... 
    } 

else 
    { 

    if (!empty($_POST)) 
     { 
     //Your database connection, insert statement...etc 
     } 
    { 

相反,你應該做這樣的事情:

if ($_SERVER["REQUEST_METHOD"] == "POST") 
    { 
     //validation code... 
     //If valid, database connection and insert statement... 
    } 

else 
    { 
    //Something else... 
    { 

當點擊submit,你的情況,它總是使用POST請求方法。並且你的代碼在不使用POST請求方法時說'做一個插入'。