Insert Backbone.js model into MySQL database

前端 未结 2 1846
甜味超标
甜味超标 2020-12-05 12:24

I have a backbone.js model with some defaults and an url:

var Box = Backbone.Model.extend({
    url: \"./save.php\",
    defaults: {
        x: 0,
        y:         


        
相关标签:
2条回答
  • 2020-12-05 12:58

    You forgot to send ID.

    //$id = $_POST['cid'];

    enter image description here

    Make Id to AUTO_INCREMENT and remove from code:

    $id = $_POST['cid'];

    mysql_query("INSERT INTO boxes (x, y, w, h)
                             VALUES('$x', '$y', '$w', '$h')
                           ") or die(mysql_error());
    
    0 讨论(0)
  • 2020-12-05 13:07

    Backbone is based on a REST API: when saving/updating a model to the server, Backbone will send it serialized as JSON in the request body with a POST our PUT request. From Backbone.sync documentation

    With the default implementation, when Backbone.sync sends up a request to save a model, its attributes will be passed, serialized as JSON, and sent in the HTTP body with content-type application/json.

    This means that server-side you have to

    • determine the type of request
    • decode the serialized JSON

    Something like this should get you started

    $request_method = strtolower($_SERVER['REQUEST_METHOD']);
    $data = null;
    
    switch ($request_method) {
        case 'post':
        case 'put':
            $data = json_decode(file_get_contents('php://input'));
        break;
    }
    
    // print_r($data);
    
    // note that mysql_* functions are deprecated
    // http://php.net/manual/en/function.mysql-query.php
    // inserting with a PDO object, assuming an auto incremented id
    $sql = "INSERT INTO boxes (x, y, w, h) VALUES(?, ?, ?, ?)";
    $sth = $dbh->prepare($sql);
    $sth->execute(array(
        $data->x,
        $data->y,
        $data->w,
        $data->h
    ));
    $id = $dbh->lastInsertId();
    

    Check this page for a more thorough implementation of a REST API in PHP http://www.gen-x-design.com/archives/create-a-rest-api-with-php/

    0 讨论(0)
提交回复
热议问题