-3

I'm making a form where I can add records to a database through the browser. When I press submit, it comes up with this error

Fatal error: Call to a member function execute() on boolean in /srv/http/career.php on line 56

Line 56 is based of this PhP line:

$result->execute($_POST);

It's not related to the connection of the database, that works because I am able to view already made records.

Full code

HTML

<form method="POST">
    <label for="jobtitle">Job Title</label> <input type="text" name="jobtitle" /> <br>
    <label for="reference">Reference</label> <input type="text" name="reference" /> <br>
    <label for="salary">Salary</label> <input type="text" name="salary"/> <br>
    <label for="location">Location</label> <input type="text" name="location"/> <br> <br>
    <label for="description">Description</label> <input type="text" name="description"/> <br> <br>
    <input type="submit" value="submit" name="submit"/>
</form>

PhP

<?php
if(isset($_POST['jobtitle'],$_POST['reference'],$_POST['salary'],$_POST['location'],$_POST['description'])){
    $result= $pdo->query('INSERT INTO jobs (job_title, job_ref, job_salary, job_location, job_desc)
        VALUES ("' . $_POST['jobtitle'] . '","' . $_POST['reference'] . '","' . $_POST['location'] . '","' . $_POST['description'] .'")');
        unset($_POST['submit']); 

    $result->execute($_POST);
}
?>

Any help is appreciated

J.Johnson
  • 19
  • 6

1 Answers1

2

Instead of using query() and concatenating values into your SQL string, try using a prepared statement like this:

$stmt = $pdo->prepare('INSERT INTO jobs (job_title, job_ref, job_salary, 
                       job_location, job_desc) VALUES (?, ?, ?, ?, ?)');
$stmt->bindValue(1, $_POST['jobtitle']);
$stmt->bindValue(2, $_POST['reference']);
$stmt->bindValue(3, $_POST['salary']);
$stmt->bindValue(4, $_POST['location']);
$stmt->bindValue(5, $_POST['description']);
$stmt->execute();

There are many benefits to this approach, including making it easier to tell when you're missing one of the values you are trying to insert (salary).

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Don't Panic
  • 41,125
  • 10
  • 61
  • 80