简体   繁体   中英

How to use backbone.js with php to save data into mysql database

I'm just getting started with backbone.js and I'm working with this tutorial on Nettuts. http://net.tutsplus.com/tutorials/javascript-ajax/getting-started-with-backbone-js/

var user = Backbone.Model.extend({
   initialize: function(){
     console.log('user was initialized!');
   },
   defaults:{
      'name' : 'wern',
      'full_name' : 'rem falkner',
      'password' : 'secret',
      'email' : 'secret@gmail.com'
   }
})

var u = new user()

And then I used the save method:

u.save(undefined, {url : 'inserts.php'})

Inserts.php contains:

<?php 
include('conn.php');

$name = $_POST['name'];
$password = md5($_POST['password']);
$email = $_POST['email'];

$db->query("INSERT INTO tbl_users SET user_id='$name', pword_hash='$password', full_name='$name', email='$email'");
?>

What's wrong with my code? It seems to be inserting in the database because whenever I call the save() method it inserts something on the user table but only in the password field.

When you call the .save() method a JSON object is sent to the url you have specified; if the model is new, the POST method will be used. When the JSON is received in the PHP script you have to decode it and save the model attributes, let us say one field per attribute. Change this in the 'inserts.php':

<?php 
    include('conn.php');

    $data = json_decode(file_get_contents('php://input'));
    $name = $data->{'name'};
    $password = md5($data->{'password'});
    $email = $data->{'email'};

    //proceed to add every variable to a field in the database
    //...

In your PHP code in the line before $db->query, do this:

echo $name, '<br>', $password, '<br>', $email;

Make a traditional HTML form with name password email fields, and test the PHP script, making sure that the name password and email address you entered appears on the screen.

If this succeeds, your error is probably in your database query. For starters, it looks like your code is vulnerable to SQL injections. You will need to post some information about what DBMS you are using (MySQL, MSSQL, PostgreSQL etc). At any rate, the query looks wrong. Also post your CREATE TABLE command.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM