2

I have a simple Backbone Application where I want to fetch the data from my MySQL Database, but I don't know how to connect to the DB. Do i have to create a folder, where in that new folder I create an index.php where I define the db-connection and all the SELECT * FROM queries etc?

My file structure is:

index.php
[css]
[js]
  [app]
    [collections]
    [models]
    [routers]
    [templates]
    [views]     
    mainpage.js
    config.js
  [lib]
    [backbone]
    [hanlebars]
    [requirejs]
    [jquery]

I guess I also have to define it in the config too?

Any suggestion is welcome...

SHT
  • 700
  • 4
  • 18
  • 39

1 Answers1

2

Backbone.js is a front-end framework. It can't connect to a MySQL database alone. You need a server-side language. As you suggested you may do this in index.php. What you have to do is to add a url property (or method) for your model or collection. The path there should point to your php file. Later when you call model.save you will receive a POST request with JSON data sent to php. Then just process the request. I.e. parse the json with json_decode and do what you usually do. Connect to the mysql server and execute queries.

Krasimir
  • 13,306
  • 3
  • 40
  • 55
  • I think we can't always guarantee that request will be POST. The request `POST` or `GET` etc. will depend on whether `id` attribute is set for the model or not. Correct me if I am wrong. – Sandeep Nayak Jan 07 '14 at 10:18
  • ah ok, so in the index.php/users.php/videos.php (or whatever) I do json_encode and in my model(s) i set urlRoot:'/users.php' and set the defaults like id, name etc? – SHT Jan 07 '14 at 10:20
  • 1
    @SandeepNayak is actually right. The method of the request depends of what you are doing. If the model is a new one then it will be POST. If you do an update it will be PUT or PATCH (I'm not sure about this one). If you destroy a model you will get DELETE and if you want to fetch it GET. – Krasimir Jan 07 '14 at 10:31
  • Check out Backbone-sql/rest – HaveAGuess May 23 '14 at 22:46