Ankit Kansara
Ankit Kansara

Reputation: 181

How to insert data to mysql using php

i have made a registration from (followed e.g from w3schools.com) where they have used the $_SERVER["PHP_SELF"] in the action of form method.

$_SERVER["PHP_SELF"] this helps for validation part but it doesn't allow to insert data into db.

I have also written code for mobile no. where only numbers should be inserted but that is also not working.Please help.

 <html>
 <head>
 <title>Meeting Room Application</title>
 </head>
 <body>
 <?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 is required";
    } else {
        $txtmob = test_input($_POST["txtmob"]);
        //check only numbers are given
        if(preg_match("/^d{10}$/", $txtmob)) {
            $mobErr = "Only numbers are allowed";
        }
    }
    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"]);
    }
}

function test_input($data) {
    $data    = trim($data);
    $data    = stripslashes($data);
    $data    = htmlspecialchars($data);
    return $data;
}
?>
<table align="center" cellpadding="5" cellspacing="5">
    <tr>
        <th colspan="2"><img src="Hitech Logo1.png" alt="HiTech"></th>
    </tr>
    <tr>
        <th colspan="2"><h1>User Registration</h1></th>
</tr>
<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" <?php if(isset($gender) && $gender == "Male") echo "checked"; ?>  value="Male">Male
            <input type="radio" name="gender" <?php if(isset($gender) && $gender == "Female") echo "checked"; ?>  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 type="text" name="txtmob" maxlength="10" value="<?php echo $txtmob ?>">
            &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 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; : </td>
        <td><input type="radio" name="role" <?php if(isset($role) && $role == "User") echo "checked"; ?>  value="User">User
            <input type="radio" name="role" <?php if(isset($role) && $role == "Admin") echo "checked"; ?>  value="Admin">Admin
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<font color="red"><?php echo $roleErr; ?>
        </td>
    </tr>
    <tr>
        <td></td>
        <td><input type="submit" value="Submit" name="btnsave">
        </td>
    </tr>
</form>
</tr>
</table>
<?php
$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      = mysqli_real_escape_string($conn, $_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        = mysqli_real_escape_string($conn, $_POST['role']);
$res         = mysqli_query($conn, "SELECT username FROM trialusers WHERE username='$username'");
$row         = mysqli_fetch_row($res);
if($row > 0) {
    echo "Username $username has already been taken";
} 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');
    }
}
?>
 </body>    
 </html>

Upvotes: 0

Views: 180

Answers (2)

Lelio Faieta
Lelio Faieta

Reputation: 6663

Change the last part of your code to this:

 <?php 
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 = mysqli_real_escape_string($conn, $_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= mysqli_real_escape_string($conn, $_POST['role']);
 $res=mysqli_query($conn,"SELECT username FROM trialusers WHERE username='$username'");
 $row=mysqli_fetch_row($res);
 if($row>0)
 {
 echo "Username $username has already been taken";
 }
 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' );
 }
 }
}
 ?> 

This will trigger the data insert part only when you actually post data from the form and will remove the error you see. BTW the code you are using is outdated and use a mysql library that is deprecated. Please consider update to PDO

Upvotes: 1

Kuldeep Dangi
Kuldeep Dangi

Reputation: 4422

It is not always possible to receive a POST request on your page so keep your bottom PHP code into a condition

if ($_SERVER["REQUEST_METHOD"] == "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 = mysqli_real_escape_string($conn, $_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= mysqli_real_escape_string($conn, $_POST['role']);
 $res=mysqli_query($conn,"SELECT username FROM trialusers WHERE username='$username'");
 $row=mysqli_fetch_row($res);
 if($row>0)
 {
 echo "Username $username has already been taken";
 }
 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' );
 }
 }
}

Upvotes: 0

Related Questions