如何使用php将数据插入mysql

时间:2015-04-20 07:19:44

标签: php mysql

我已经从(例如来自w3schools.com)进行了注册,他们在表单方法的操作中使用了$_SERVER["PHP_SELF"]

$_SERVER["PHP_SELF"]这有助于验证部分,但它不允许将数据插入db。

我还为手机编写代码。只应插入数字,但也无法使用。请帮助。

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

2 个答案:

答案 0 :(得分:1)

将代码的最后一部分更改为:

 <?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' );
 }
 }
}
 ?> 

仅当您实际从表单发布数据时才会触发数据插入部分,并将删除您看到的错误。 BTW您使用的代码已过时,并使用不推荐使用的mysql库。请考虑更新到PDO

答案 1 :(得分:0)

并非总能在您的网页上收到POST请求,因此请将最底层的PHP代码保留在条件中

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' );
 }
 }
}