You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Ajax+PHP无刷新提交数据报错:Call to a member function prepare() on boolean

Fixing "Call to a member function prepare() on boolean" Error in Ajax-PHP Form Submission

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 of localhost=
  • Kept the PDO connection instance in $conn instead of overwriting it
  • Added charset=utf8mb4 to 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 null from the INSERT INTO column list (assuming your users table 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:32:58