未捕获的错误:在布尔值上调用成员函数prepare()...堆栈跟踪:抛出#0 {main}

时间:2019-03-19 12:10:58

标签: javascript php jquery ajax

我正在尝试使用Ajax和PHP发送我的输入数据数据库而不刷新页面。但是我遇到了这个错误,已经花了几个小时解决了这个问题,但我仍然做不到。请帮我。谢谢!

这是我的index.php文件,我在其中放置了ajax脚本和html代码。

  $(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();
        }
      });
    });
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></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>

<div class="alert alert-success" role="alert" id="result"></div>

这是我的insert.php文件

<?php 


    try {

        include_once 'classes/Db.php';

        $fullname = addslashes($_POST['fullname']);
        $address = addslashes($_POST['address']);

        $sql = "INSERT INTO users (null, fullname, address) VALUES ('$fullname', '$address')";
        $stmt = $conn->prepare($sql);
        $stmt->execute();

    } catch (PDOException $e) {
        echo "ERROR IN INSERTING DATA! : " . $e->getMessage();
    }

?>

还有我的classes / Db.php文件

<?php       

    $localhost = 'localhost';
    $dbname = 'test_icon';
    $username = 'root';
    $password = '';

    try {

        $sql = 'mysql:localhost=' .$localhost. '; dbname=' .$dbname;
        $stmt = new PDO($sql, $username, $password);
        $conn = $stmt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    } catch (PDOException $e) {
        echo "CONNECTION FAILED: " .$e->getMessage(). '<br/>';
        die();
    }

?>

2 个答案:

答案 0 :(得分:2)

在创建PDO实例时,您正在将连接设置为setAttribute的结果,该结果是一个布尔值,指示函数是否成功。您应该将其设置为构造函数的输出:

$conn = new PDO($sql, $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

答案 1 :(得分:1)

首次修复;

$sql = 'mysql:localhost=' .$localhost. '; dbname=' .$dbname;

应该是:

$sql = 'mysql:host=' .$localhost. '; dbname=' .$dbname;

然后:

$sql = "INSERT INTO users (fullname, address) VALUES (?,?)";
$stmt = $conn->prepare($sql);
$stmt->execute([$fullname,$address]);