Daniel
Daniel

Reputation: 4342

javascript post to database

I am trying to save data into a database using POST and AJAX. The script runs as a user script for Firefox. When I run the script no errors is shown and nothing appears in the database.

PHP

    $db_connection = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
    //$db_connection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );  
    //$db_connection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );  
    //$db_connection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

    $insert_key = $db_connection->prepare("INSERT into userstats (key, match, expire) VALUES (?, ?, ?, ?)");
    $insert_key->bindParam(1, $_POST["user"]);
    $insert_key->bindParam(2, $_POST["score"]);
    $insert_key->bindParam(3, $_POST["location"]);
    $insert_key->bindParam(4, $_POST["pointtime"]);
    $insert_key->execute();

    $db_connection = null;

    echo "saved to database!";

} catch(PDOException $e) {
    echo $e->getMessage();
}

javascript

xhr = new XMLHttpRequest();
xhr.open("POST", "stats.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", params.length);
xhr.setRequestHeader("Connection", "close");
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
        console.log(xhr.responseText);
    }
}

var params = "?user=james&score=5&location=homepage&pointtime=1350249055";
xhr.send(params);

Upvotes: 1

Views: 109

Answers (1)

Michael Berkowski
Michael Berkowski

Reputation: 270609

KEY and MATCH are MySQL reserved keywords, so your statement is not being properly prepared. Enclose them in backticks to use it as a column name:

 $insert_key = $db_connection->prepare("INSERT into userstats (`key`, `match`, expire) VALUES (?, ?, ?, ?)");

As for why it didn't throw an exception, make sure you actually have PDO configured to throw exceptions. If you don't, the $insert_key will be FALSE and you'll get E_WARNINGs for the subsequent attempts to bind params and execute it.

I would recommend making sure error_reporting() is enabled and display_errors is on, so in case you aren't getting exceptions thrown and instead got a fatal error that caused your script to terminate, you would at least see the error output returned back to the AJAX caller in your console.log()

ini_set('display_errors', 1);
error_reporting(E_ALL);

Upvotes: 3

Related Questions