dot_0620 2016-02-21 13:43 采纳率: 100%
浏览 59
已采纳

JS对象为PHP,然后通过PDO INSERT

I have this JS Object:

var planet = {
owner: 4,
name: "Mars",
loc: [3, 4],
level: 4,
baseIncome: 1000
}

I use ajax to transfer this object to PHP

postPlanets: function(planet){

    planet = JSON.stringify(planet);

    $.ajax({
        type: "POST",
        url: "postGameData.php",
        datatype: "json",
        data: {planet: planet}, 
        error: ajax.error,
        success: ajax.success,
    });

I decode the JSON on php via

if (isset($_POST["planet"]{
    $planet = JSON_decode($_POST["planet"]);
}

I then try to do an INSERT using PDO

public function insertPlanet($planet){

    $stmt = $this->connection->prepare("
        INSERT INTO planets
            (owner, name, x, y, level, baseIncome)
        VALUES
            (:owner, :name, :x, :y, :level, :baseIncome)
    ");

    $stmt->bindParam(":owner", $planet["owner"]);
    $stmt->bindParam(":name", $planet["name"]);
    $stmt->bindParam(":x", $planet["loc"][0]);
    $stmt->bindParam(":y", $planet["loc"][1]);
    $stmt->bindParam(":level", $planet["level"]);
    $stmt->bindParam(":baseIncome", $planet["baseIncome"]);

    $stmt->execute();

    if ($stmt->errorCode() == 0){
        return true;
    }
    else {
        return false;
    }
}

But its not working. I know it breaks once it tries to bind the very first parameter on PDO, but i dont know either way nor how i could possibly debug the prepared statement at all.

What am i doing wrong ?

ERROR RETURN

object(stdClass)#3 (5) {
  ["owner"]=>
  string(3) "sdf"
  ["name"]=>
  string(3) "sdf"
  ["loc"]=>
  array(2) {
    [0]=>
    int(2)
    [1]=>
    int(4)
  }
  ["level"]=>
  string(3) "sdf"
  ["baseIncome"]=>
  string(1) "f"
}
<br />
<b>Fatal error</b>:  Cannot use object of type stdClass as array in <b>D:\SecureWAMP_Portable\htdocs\projectX\DBManager.php</b> on line <b>285</b><br />

285 is the very first BIND attempt.

  • 写回答

2条回答 默认 最新

  • dsgoj7457 2016-02-21 14:15
    关注

    if it's object I think you can call like $planet->owner not like array $planet['owner'].

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用