使用Ajax+PHP无刷新提交数据报错:Call to a member function prepare() on boolean
Hey there, let's break down what's causing that error and get your form working without page refreshes! The error you're seeing means your $conn variable isn't a valid PDO connection object (it's a boolean instead), plus there are a couple of other issues in your SQL and setup. Let's fix them one by one:
1. Fix the Database Connection (classes/Db.php)
Your DSN string is formatted incorrectly, and you're overwriting the PDO instance with the boolean result of setAttribute. Here's the corrected version:
<?php $localhost = 'localhost'; $dbname = 'test_icon'; $username = 'root'; $password = ''; try { // Correct DSN format: mysql:host=...;dbname=... $dsn = "mysql:host=$localhost;dbname=$dbname;charset=utf8mb4"; // Create and store the PDO connection instance first $conn = new PDO($dsn, $username, $password); // Set error mode to exceptions (this method doesn't return a value to assign) $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { echo "CONNECTION FAILED: " . $e->getMessage() . '<br/>'; die(); } ?>
Key fixes here:
- Corrected the DSN string to use
host=instead oflocalhost= - Kept the PDO connection instance in
$conninstead of overwriting it - Added
charset=utf8mb4to ensure proper character encoding for your data
2. Fix the Insert Query (insert.php)
Your SQL syntax is invalid (you included null in the column list), and you're using unsafe string concatenation. Let's switch to secure prepared statements:
<?php try { include_once 'classes/Db.php'; // Valid SQL syntax: omit auto-incrementing primary key (like `id`) from columns $sql = "INSERT INTO users (fullname, address) VALUES (:fullname, :address)"; $stmt = $conn->prepare($sql); // Bind parameters safely to avoid SQL injection $stmt->bindParam(':fullname', $_POST['fullname'], PDO::PARAM_STR); $stmt->bindParam(':address', $_POST['address'], PDO::PARAM_STR); $stmt->execute(); echo "Data inserted successfully!"; } catch (PDOException $e) { echo "ERROR IN INSERTING DATA! : " . $e->getMessage(); } ?>
Key fixes here:
- Removed
nullfrom theINSERT INTOcolumn list (assuming youruserstable has an auto-incrementing primary key that doesn't need manual input) - Used named placeholders (
:fullname,:address) instead of string interpolation to prevent SQL injection - Added a clear success message to return to the Ajax call
3. Minor Fix to Your Ajax Script
Your jQuery library is loaded after your custom script, which will cause a "jQuery is not defined" error. Move the library tag above your script, plus add an error handler for debugging:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function() { $('#myForm').submit(function(event) { event.preventDefault(); $.ajax({ url: 'insert.php', method: 'post', data: $('form').serialize(), dataType: 'text', success: function(strMessage) { $('#result').text(strMessage); $('#myForm')[0].reset(); }, // Add error handling to catch Ajax-related issues error: function(xhr, status, error) { $('#result').text("Ajax request failed: " + error); } }); }); }); </script> <h5 class="alert-heading"> ADD INFORMATION </h5> <hr> <form id="myForm" method="post" action=""> <div class="form-group"> <label>Full name</label> <input type="text" autofocus="on" class="form-control" name="fullname" placeholder="Enter your name here" required> </div> <div class="form-group"> <label>Address</label> <input type="text" class="form-control" name="address" placeholder="Address" required> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> <div class="alert alert-success" role="alert" id="result"></div>
Key fix here:
- Moved the jQuery library script above your custom code so jQuery is available when your script runs
- Added an error handler to help debug any issues with the Ajax request itself
After making these changes, your form should submit data to the database without page refreshes, and the original error should be resolved!
内容的提问来源于stack exchange,提问作者Jasper Santiago

