0

I am new to using PDO and I am getting an http 500 server error when the form is submitted.

The php page with the processing code is in the correct folder so I don't know why its throwing up a 500 error.

There is NO url rewrite going on neither .

Here is my code:

        try {
        $dbh = new PDO("mysql:host=$hostname;dbname=crm",$username,$password);

        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line

        $stmt = $db->prepare("INSERT INTO testdrives (forename, surname,phone,email,add1,add2,add3,city,county,postcode,car,date) VALUES (:forename, :surname,:phone,:email,:add1,:add2,:add3,:city,:county,:postcode,:car,:date)");
                $stmt->bindParam(':forename', $_POST['forename']);
                $stmt->bindParam(':surname', $_POST['surname']);
                $stmt->bindParam(':phone', $_POST['phone']);
                $stmt->bindParam(':email', $_POST['email']);
                $stmt->bindParam(':add1', $_POST['add1']);
                $stmt->bindParam(':add2', $_POST['add2']);
                $stmt->bindParam(':add3', $_POST['add3']);
                $stmt->bindParam(':city', $_POST['city']);
                $stmt->bindParam(':county', $_POST['county']);
                $stmt->bindParam(':postcode', $_POST['postcode']);
                $stmt->bindParam(':car', $_POST['car']);
                $stmt->bindParam(':date', $_POST['date']);
                $stmt->execute();
        if ($dbh->query($sql)) {
        echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
        }
        else{
        echo "<script type= 'text/javascript'>alert('Data not successfully Inserted.');</script>";
        }

        $dbh = null;
        }
        catch(PDOException $e)
        {
        echo $e->getMessage();
        }
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Chris Yates
  • 65
  • 10

2 Answers2

3

Edit:

I missed the incorrect variable used for the connection being $dbh and $db in the prepare; my bad.


Original answer.

This line:

if ($dbh->query($sql)) {...}

is failing for two reasons:

  • Calling query() on what is already being prepared/executed.
  • Using a non-existant variable, $sql.

Get rid of that statement with the related brace and replace it with simply and replacing the $stmt->execute(); with:

if($stmt->execute()){

        // success

    } else{

        // error

    }

and using PDO's error handling (as you are doing now) and PHP's error reporting:

Check your logs also.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
0

Found the problem

The above code shows

$stmt = $db->prepare

Needed to be changed to

$stmt = $dbh->prepare

Thanks for help with the other issue

Quick question how to i insert into a table that has an auto increment column ?

Chris Yates
  • 65
  • 10