0

I'm trying to use Ajax and PHP to send my input data database without refreshing the page. But I am getting this error and it's been couple of hours of me solving this issue but I still can't. Please help me. Thanks!

This is my index.php file where I placed my ajax script and html codes.

  $(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>

And here's my insert.php file

<?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();
    }

?>

And my classes/Db.php file

<?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();
    }

?>
Dharman
  • 30,962
  • 25
  • 85
  • 135
  • this might help https://stackoverflow.com/questions/37797851/fatal-error-call-to-a-member-function-prepare-on-boolean-in – Carsten Løvbo Andersen Mar 19 '19 at 12:13
  • 1
    `localhost=' .$localhost. '` should probably be `host=' .$localhost. '`. `$stmt = new PDO` should probably be `$conn = new PDO` and `$conn = $stmt->setAttribute(`, just `$conn->setAttribute(`. – Jonnix Mar 19 '19 at 12:13
  • Your script is wide open to [SQL Injection Attack](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) Even [if you are escaping inputs, its not safe!](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) Use [prepared parameterized statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) in either the `MYSQLI_` or `PDO` API's – RiggsFolly Mar 19 '19 at 12:14
  • __Additional Note___ This query `INSERT INTO users (null, fullname, address) VALUES ('$fullname', '$address')` DOES NOT protect you from SQL Injection as you added the concatenated values BEFORE preparing the query – RiggsFolly Mar 19 '19 at 12:15
  • Correct duplicate: https://stackoverflow.com/q/32648371/1839439 – Dharman Nov 01 '19 at 19:05

2 Answers2

2

When you create your PDO instance you are setting the connection to the result of setAttribute which is a boolean indicating whether the function succeeded or not. You should be setting it to the output of the constructor:

$conn = new PDO($sql, $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Nick
  • 138,499
  • 22
  • 57
  • 95
2

First fix ;

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

Should be :

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

Then :

$sql = "INSERT INTO users (fullname, address) VALUES (?,?)";
$stmt = $conn->prepare($sql);
$stmt->execute([$fullname,$address]);
Dharman
  • 30,962
  • 25
  • 85
  • 135
Masivuye Cokile
  • 4,754
  • 3
  • 19
  • 34