weixin_33686714 2012-10-14 21:44 采纳率: 0%
浏览 21

javascript发布到数据库

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);
  • 写回答

1条回答 默认 最新

  • 乱世@小熊 2012-10-14 21:47
    关注

    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);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题