简体   繁体   中英

Submitting the form values into MySql

I have made a registration page in php where i have given validation for new user registration. The issue is that the values are not getting inserted into MySql db. I want the data to be inserted into the MySql.One More issue is that on click of submit the data field should be empty. Please Help!

<?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>

You can't output any HTML before calling header() , so you have to do that at the end, not the beginning. You should also call exit() after header('location:registration.php') , because the output is ignored when you're redirecting. This will solve the problem of the form not being cleared when the insert is successful.

I don't see a problem with the INSERT statement, so I can't explain why it's not inserting.

<?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>

First of all, there is a problem with your if statement, as a result, your insert query is never reached.

This is what you have:

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

else
   {

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

Instead, you should do something like this:

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

else
   {
    //Something else...
   { 

When submit is clicked, in your case, it will always use POST request method. And your code says 'do a insert' when NOT using POST request method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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