Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

Archive /

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

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

Conecting to external database + using SilverStripe objects


Reply


2 Posts   2069 Views

Avatar
danielbenedykt

Community Member, 9 Posts

2 June 2008 at 11:41am

Edited: 02/06/2008 11:41am

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

Avatar
danielbenedykt

Community Member, 9 Posts

5 June 2008 at 3:47am

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

:)