简体   繁体   English

如何使用backbone.js与php将数据保存到mysql数据库中

[英]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. 我刚刚开始使用backbone.js,我正在使用Nettuts上的这个教程。 http://net.tutsplus.com/tutorials/javascript-ajax/getting-started-with-backbone-js/ 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: 然后我使用了save方法:

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

Inserts.php contains: Inserts.php包含:

<?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. 它似乎是插入数据库中,因为无论何时调用save()方法,它都会在用户表上插入一些内容,但只能在密码字段中插入。

When you call the .save() method a JSON object is sent to the url you have specified; 当您调用.save()方法时,JSON对象将被发送到您指定的URL; if the model is new, the POST method will be used. 如果模型是新的,将使用POST方法。 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. 当在PHP脚本中收到JSON时,您必须解码它并保存模型属性,让我们说每个属性一个字段。 Change this in the 'inserts.php': 在'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: 在$ db-> query之前的行中的PHP代码中,执行以下操作:

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. 制作带有名称密码电子邮件字段的传统HTML表单,并测试PHP脚本,确保您输入的名称密码和电子邮件地址显示在屏幕上。

If this succeeds, your error is probably in your database query. 如果成功,则您的错误可能在数据库查询中。 For starters, it looks like your code is vulnerable to SQL injections. 对于初学者来说,您的代码看起来很容易受到SQL注入攻击。 You will need to post some information about what DBMS you are using (MySQL, MSSQL, PostgreSQL etc). 您需要发布一些有关您正在使用的DBMS的信息(MySQL,MSSQL,PostgreSQL等)。 At any rate, the query looks wrong. 无论如何,查询看起来不对。 Also post your CREATE TABLE command. 同时发布您的CREATE TABLE命令。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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