PHP+MySQL报错求助:mysqli未定义及表单验证与数据入库问题
Hey there! Let's break down your problems step by step, starting with those frustrating error messages you're seeing.
Undefined variable: mysqli & Call to a member function prepare() on null Errors These two errors stem from the same core issue: your $mysqli variable isn't properly set up (or doesn't exist) before you try to use it on line 20. Here's how to fix this:
First, you need to establish a valid connection to your MySQL database using MySQLi before running any queries. Add this code at the top of your register.php file (definitely above line 20):
// Replace these with your actual database details (XAMPP defaults are below) $host = 'localhost'; $dbUsername = 'root'; // Default XAMPP username $dbPassword = ''; // Default XAMPP password is empty $dbName = 'your_database_name'; // Replace with your database's name // Create the MySQLi connection $mysqli = new mysqli($host, $dbUsername, $dbPassword, $dbName); // Check if the connection failed if ($mysqli->connect_error) { die("Connection failed: " . $mysqli->connect_error); }
If you already had connection code, double-check that it's placed before line 20 and that there are no typos in the variable name (like misspelling mysqli as mysql).
You should always do validation in two places: client-side (HTML/JS) for quick user feedback, and server-side (PHP) to keep things secure (since client-side validation can be easily bypassed).
Client-Side Validation (Basic HTML5)
Add validation attributes directly to your form fields for instant checks:
<form action="register.php" method="POST"> <label for="username">Username:</label> <input type="text" id="username" name="username" required minlength="3" maxlength="20" pattern="[a-zA-Z0-9]+" title="Username can only use letters and numbers, 3-20 characters."> <label for="email">Email:</label> <input type="email" id="email" name="email" required> <label for="password">Password:</label> <input type="password" id="password" name="password" required minlength="8" title="Password needs to be at least 8 characters long."> <button type="submit">Register</button> </form>
required: Makes sure the field can't be left emptyminlength/maxlength: Limits how long/short the input can betype="email": Automatically checks for a valid email formatpattern: Uses a regex to restrict allowed characters
Server-Side Validation (PHP)
Add this code right after your database connection in register.php to validate submitted data securely:
if ($_SERVER['REQUEST_METHOD'] === 'POST') { $errors = []; // Check username if (empty($_POST['username'])) { $errors[] = "Username is required."; } elseif (!preg_match("/^[a-zA-Z0-9]{3,20}$/", $_POST['username'])) { $errors[] = "Username must be 3-20 characters and only use letters/numbers."; } // Check email if (empty($_POST['email'])) { $errors[] = "Email is required."; } elseif (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) { $errors[] = "Please enter a valid email address."; } // Check password if (empty($_POST['password'])) { $errors[] = "Password is required."; } elseif (strlen($_POST['password']) < 8) { $errors[] = "Password must be at least 8 characters long."; } // If no errors, move to database insertion if (empty($errors)) { // Database insert code goes here (see section 3) } else { // Show errors to the user foreach ($errors as $error) { echo "<p style='color: red;'>$error</p>"; } } }
Now that your connection is fixed and validation is set up, use prepared statements (which you were already trying to do!) to safely insert data into your table. This prevents SQL injection attacks, which are a critical security risk.
Assuming you have a users table with columns id (auto-increment primary key), username, email, password, add this code inside the if (empty($errors)) block:
// Hash the password (NEVER store plain text passwords!) $hashedPassword = password_hash($_POST['password'], PASSWORD_DEFAULT); // Prepare the insert query $stmt = $mysqli->prepare("INSERT INTO users (username, email, password) VALUES (?, ?, ?)"); // Bind parameters (s = string, s = string, s = string) $stmt->bind_param("sss", $_POST['username'], $_POST['email'], $hashedPassword); // Run the query if ($stmt->execute()) { echo "<p style='color: green;'>Registration successful!</p>"; } else { echo "<p style='color: red;'>Error: " . $stmt->error . "</p>"; } // Clean up $stmt->close(); $mysqli->close();
A key reminder: Always hash passwords with password_hash() — storing plain text passwords is a huge no-no for user security.
内容的提问来源于stack exchange,提问作者user9355654

