How to correctly handle PHP form submission
Overview:
In the process of website development, form submission is a very common operation. As a programming language widely used in web development, PHP provides a wealth of functions and methods to handle form submission. This article will introduce how to correctly handle PHP form submission and provide some example code for reference.
1. Basic steps of form processing:
<form action="submit.php" method="post"> <input type="text" name="username" placeholder="请输入用户名" required> <input type="password" name="password" placeholder="请输入密码" required> <input type="submit" value="提交"> </form>
$username = $_POST['username']; $password = $_POST['password'];
if(strlen($username) < 6 || strlen($username) > 16){ echo "用户名长度必须在6-16个字符之间"; exit; } $username = htmlspecialchars($username);
// 连接数据库 $conn = mysqli_connect("localhost", "root", "password", "database"); // 检查连接是否成功 if (!$conn) { die("连接数据库失败: " . mysqli_connect_error()); } // 执行插入操作 $sql = "INSERT INTO users (username, password) VALUES ('$username', '$password')"; if (mysqli_query($conn, $sql)) { echo "数据提交成功"; } else { echo "数据提交失败: " . mysqli_error($conn); } // 关闭数据库连接 mysqli_close($conn);
2. Common form processing problems and solutions:
if(empty($username) || empty($password)){ echo "用户名和密码不能为空"; exit; }
if(strlen($username) < 6 || strlen($username) > 16){ echo "用户名长度必须在6-16个字符之间"; exit; }
$sql = "SELECT * FROM users WHERE username = ? AND password = ?"; $stmt = mysqli_prepare($conn, $sql); mysqli_stmt_bind_param($stmt, "ss", $username, $password); mysqli_stmt_execute($stmt); $result = mysqli_stmt_get_result($stmt); while ($row = mysqli_fetch_assoc($result)) { // 处理结果集 } mysqli_stmt_close($stmt);
$username = htmlspecialchars($_POST['username']);
Conclusion:
Through the above steps, we can correctly handle PHP form submission and avoid some common form processing problems. Of course, in the specific development process, corresponding adjustments and improvements must be made according to business needs. Finally, I hope this article will be helpful to you when dealing with PHP form submissions.
The above is the detailed content of How to properly handle PHP form submission. For more information, please follow other related articles on the PHP Chinese website!