多表项的PHP表单提交

时间:2017-05-01 10:26:22

标签: php forms

成功插入后如何保持当前表单的清晰字段。我习惯使用php文件,一个用于连接数据库,另一个用于从用户收集数据。两个文件代码如下: 用于连接数据库:

<?php
$servername = "localhost";
$username = "local";
$password = "host";
$dbname = "form";

$conn = mysqli_connect($servername,$username,$password,$dbname);

if(!$conn){
    die("Connection failed: ".mysqli_connect_error());
}

$roll=$_POST['roll'];
$name=$_POST['name'];
$city=$_POST['city'];

$sql = "insert into people_info (roll,name,city) values ('$roll','$name','$city')";


if(mysqli_query($conn,$sql)){
    echo "New record created successflly";
}
else{
    echo "Error: ".$sql."<br>".mysqli_error($conn);
}

mysqli_close($conn);
?>

表单页面是:

<html>
<body>

<form action="connection.php" method="post">
    <table border="1">
        <tr>
            <th>
                Field
            </th>
            <th>
                Value
            </th>
        </tr>
        <tr>
            <td>
                Roll:
            </td>
            <td>
                <input type="text" name="roll"/><br>
            </td>
        </tr>
        <tr>
            <td>
                Name:
            </td>
            <td>
                <input type="text" name="name"/><br>
            </td>
        </tr>
        <tr>
            <td>
                City:
            </td>
            <td>
                <input type="text" name="city"/><br>
            </td>
        </tr>
        <tr>
            <td>
                <input type="submit"/>
            </td>
        </tr>
    </table>
</form>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

而不是:

if(mysqli_query($conn,$sql)){
    echo "New record created successfully";
}
else{
    echo "Error: ".$sql."<br>".mysqli_error($conn);
}

尝试

if(mysqli_query($conn,$sql)){
    header('location: page1.php?message=New record created successfully');
}
else{
    header('location: page1.php?message=' . mysqli_error($conn));
}

此处header()函数会将您重定向到包含响应消息的$message变量的表单页面。用它来显示页面上的响应。