php - Insert Backbone.js model into MySQL database -
i have backbone.js model defaults , url:
var box = backbone.model.extend({ url: "./save.php", defaults: { x: 0, y: 0, w: 1, h: 1 } });
then have instance of model , proceed save it:
var box = new box({ x:10, y:10, w:200, h:200 }); box.save();
now want save model mysql database using php script "save.php", goes this:
<?php include('connection.php'); $id = $_post['cid']; $x = $_post['x']; $y = $_post['y']; $w = $_post['w']; $h = $_post['h']; mysql_query("insert boxes (id, x, y, w, h) values('$id', '$x', '$y', '$w', '$h') ") or die(mysql_error()); ?> echo "data inserted!";
i have tried reading many tutorials cannot simple model save work. why code not working? ideas on how can solved?
thanks
edit: quick solution
in php script, correct way obtain information sent json object follows:
$box_data = json_decode(file_get_contents('php://input')); $x = $box_data->{'x'}; $y = $box_data->{'y'}; $w = $box_data->{'w'}; $h = $box_data->{'h'};
and store in in database:
mysql_query("insert boxes(id, x, y, w, h) values('', '$x', '$y', '$w', '$h') ") or die(mysql_error());
in way 1 row inserted in table "boxes" information of each 1 of attributes of backbone model box. server request method in case post , id in table "boxes" set auto-increment.
backbone based on rest api: when saving/updating model server, backbone send serialized json in request body post
our put
request. backbone.sync documentation
with default implementation, when backbone.sync sends request save model, attributes passed, serialized json, , sent in http body content-type application/json.
this means server-side have to
- determine type of request
- decode serialized json
something should 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 mysql_* functions deprecated // http://php.net/manual/en/function.mysql-query.php // inserting pdo object, assuming auto incremented id $sql = "insert 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 page more thorough implementation of rest api in php http://www.gen-x-design.com/archives/create-a-rest-api-with-php/
Comments
Post a Comment