Jump to:

17452 Posts in 4473 Topics by 1971 members

Archive

SilverStripe Forums » Archive » Conecting to external database + using SilverStripe objects

Our old forums are still available as a read-only archive.

Moderators: martimiz, Sean, biapar, Willr, Ingo, simon_w

Page: 1
Go to End
Author Topic: 2001 Views
  • danielbenedykt
    Avatar
    Community Member
    9 Posts

    Conecting to external database + using SilverStripe objects Link to this post

    Hi

    So I have to integrate Silverstripe with an external database.

    I did this following the answers from this forum post
    http://www.silverstripe.com/extending-hacking-silverstripe-forum/flat/120

    On the ProductPage_Controller class I have the following function:

    function Products($num=5) {
       $db = new MySQLDatabase(array("server" => "localhost","username" => "root","password" => "","database" => "prods" ));
    $query = $db->query("SELECT * FROM products");
    $result = new DataObjectSet();
    foreach($query as $row) {
    //Debug::show($row);
    $a = new MyProduct($row);
    //Debug::show($a);
    $result->push($a);
    }

    If I use the debug function on the $row, I can see the data.
    Then I create a class MyProduct extends ViewableData
    So I can put the data in Silverstripe objects

    My question is where and how should I define the fields for MyProduct object?

    Also I have a ProductPage.ss file where I have a <% control Products %> call.
    This will call the Products function and if I have for example 3 products, It will iterate 3 times.
    If inside the <% control Products %> I write $name (a field returned by the SQL) it doesn't show anything, probably because I didn't define the fields of MyProduct object.

    I hope this is a clear picture of my situation.

    Thanks for the help

    Daniel

  • danielbenedykt
    Avatar
    Community Member
    9 Posts

    Re: Conecting to external database + using SilverStripe objects Link to this post

    Hi

    After a couple of days I manage to fix the problem by myself.

    Here is the solution:

    Instead of defining an object in code (MyProduct class) I convert the result using the ArrayData class.
    I used the following code:

    $result = new DataObjectSet();
    foreach($query as $row) {
    $result->push(new ArrayData($row));
    }

    So I get a dataobjectset with all the information inside.

    Then I can use the information on the ProductPage.ss page

    2001 Views
Page: 1
Go to Top

Want to know more about the company that brought you SilverStripe? Then check out SilverStripe.com

Comments on this website? Please give feedback.