3

I get this error when i'm executing my code. I know this has been discussed a several times here but i couldn't solve my problem by reading the solutions provided there.

This is the error i get: Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error: 2031

This is my code:

function insertMarker(){

    $lat = $_POST['lat'];
    $long = $_POST['long'];
    $street = $_POST['street'];
    $city = $_POST['city'];
    $zip = $_POST['zip'];

    echo ("$lat, $long, $street, $city, $zip");
    global $dbconnect;
    $query = $dbconnect->query("INSERT INTO address (latitude, longitude, street, city, zip) VALUES (?,?,?,?,?)");
        $query->bindParam(1, $lat);
        $query->bindParam(2, $long);
        $query->bindParam(3, $street);
        $query->bindParam(4, $city);
        $query->bindParam(5, $zip);
        $query->execute();

        //$query->execute(array(":lat"=>$lat, ":long"=>$long,":street"=>$street,":city"=>$city,":zip"=>$zip));
}
dan
  • 873
  • 8
  • 11
  • 3
    If `dbconnect` is an instance of `PDO` then query both creates a [prepared statement and then executes it all in one go](http://php.net/manual/en/pdo.query.php). So its not getting the parameters bound initially. use [`PDO::prepare`](http://php.net/manual/en/pdo.prepare.php) instead of `PDO::query`. – prodigitalson Dec 07 '14 at 00:10
  • 2
    @prodigitalson thank you!! PDO::prepare was the solution! – dan Dec 07 '14 at 00:15

2 Answers2

3

Just making my comment an answer:

If dbconnect is an instance of PDO then query both creates a prepared statement and then executes it all in one go. So its not getting the parameters bound initially. Use PDO::prepare instead of PDO::query.

prodigitalson
  • 60,050
  • 10
  • 100
  • 114
0

Try

function insertMarker(){
    $lat = $_POST['lat'];
    $long = $_POST['long'];
    $street = $_POST['street'];
    $city = $_POST['city'];
    $zip = $_POST['zip'];

    echo ("$lat, $long, $street, $city, $zip");
    global $dbconnect;
    $query = $dbconnect->prepare("INSERT INTO address (latitude, longitude, street, city, zip) VALUES (?,?,?,?,?)");
    $query->bindParam(1, $lat);
    $query->bindParam(2, $long);
    $query->bindParam(3, $street);
    $query->bindParam(4, $city);
    $query->bindParam(5, $zip);

    $query->execute(array(":lat"=>$lat, ":long"=>$long,":street"=>$street,":city"=>$city,":zip"=>$zip));

}

iatboy
  • 1,295
  • 1
  • 12
  • 19
  • You should not use `bindParam` and then also use the params as the argument to execute, you should use 1 or the other. [The params in `execute` take precedence of those bound with `bindParam` and it can result in un-bound parameters if there is a difference](http://stackoverflow.com/a/17274928/215966). – prodigitalson Dec 07 '14 at 01:18