PHP表单添加按钮输入验证及PDO INSERT实现求助(新手)
Hey there! Since you're just starting out with PHP, I'll walk you through this step by step, keeping things simple and focused on exactly what you need. Let's split this into two core parts: input validation and PDO database insertion.
1. The HTML Form
First, let's build the basic form with your required fields (username, age, amount) and an "Add" button. We'll use the POST method since we're handling user-submitted data:
<!DOCTYPE html> <html> <head> <title>Add User Data</title> </head> <body> <!-- Display validation errors here if any --> <?php if (!empty($errors)): ?> <div style="color: red;"> <?php foreach ($errors as $error): ?> <p><?php echo $error; ?></p> <?php endforeach; ?> </div> <?php endif; ?> <form method="POST" action=""> <div> <label for="username">Username:</label> <input type="text" name="username" id="username" value="<?php echo isset($_POST['username']) ? htmlspecialchars($_POST['username']) : ''; ?>"> </div> <div> <label for="age">Age:</label> <input type="text" name="age" id="age" value="<?php echo isset($_POST['age']) ? htmlspecialchars($_POST['age']) : ''; ?>"> </div> <div> <label for="amount">Amount:</label> <input type="text" name="amount" id="amount" value="<?php echo isset($_POST['amount']) ? htmlspecialchars($_POST['amount']) : ''; ?>"> </div> <button type="submit" name="add_btn">Add</button> </form> </body> </html>
Note: We use htmlspecialchars() to repopulate form fields safely—this prevents XSS attacks, a good habit to pick up early!
2. PHP Validation & PDO Insert Logic
Put this code at the top of your PHP file (before the HTML). It handles form submission, validates inputs, and only inserts data if everything checks out:
<?php // Initialize an array to store validation error messages $errors = []; // Check if the "Add" button was clicked (i.e., we have a POST request) if (isset($_POST['add_btn'])) { // 1. Validate Username: Ensure it's not empty $username = trim($_POST['username'] ?? ''); if (empty($username)) { $errors[] = "Username is required"; } // 2. Validate Age & Amount: Ensure both are numeric $age = $_POST['age'] ?? ''; $amount = $_POST['amount'] ?? ''; // Use is_numeric() to check if values are valid numbers (works for strings like "25" too) if (!is_numeric($age) || !is_numeric($amount)) { $errors[] = "Data must be numeric"; } // If no validation errors, proceed to insert into the database if (empty($errors)) { // -------------------------- // PDO Database Insertion // -------------------------- try { // Replace these with your actual database credentials $dsn = 'mysql:host=localhost;dbname=your_database_name;charset=utf8mb4'; $db_user = 'your_db_username'; $db_pass = 'your_db_password'; // Create a PDO connection with error mode set to exceptions (easier debugging) $pdo = new PDO($dsn, $db_user, $db_pass); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Prepare the INSERT statement (uses placeholders to prevent SQL injection!) $sql = "INSERT INTO your_table_name (username, age, amount) VALUES (:username, :age, :amount)"; $stmt = $pdo->prepare($sql); // Bind values to the placeholders (specify data types for safety) $stmt->bindParam(':username', $username, PDO::PARAM_STR); $stmt->bindParam(':age', $age, PDO::PARAM_INT); // Use PARAM_INT since age is an integer $stmt->bindParam(':amount', $amount, PDO::PARAM_STR); // Use PARAM_STR if amount has decimals, PARAM_INT if it's whole numbers // Execute the statement $stmt->execute(); // Optional: Show a success message echo "<p style='color: green;'>Data added successfully!</p>"; // Clear form fields after successful submission $username = $age = $amount = ''; } catch (PDOException $e) { // Catch and display database errors $errors[] = "Database error: " . $e->getMessage(); } finally { // Close the PDO connection (optional, but good practice) $pdo = null; } } } ?>
Quick Tips for Beginners
is_numeric()Quirk: This function returnstruefor both integers (like30) and numeric strings (like"30"), which is perfect since form inputs are always strings.- Prepared Statements: Using placeholders (
:username,:age) is non-negotiable—it stops attackers from injecting malicious SQL into your database. - Error Handling: The
try/catchblock helps you spot issues like wrong database credentials or missing tables without breaking the whole page. - Trimmed Username:
trim()removes extra spaces from the username, so users can't submit just blank spaces as a valid entry.
内容的提问来源于stack exchange,提问作者Milton Hunter

