How to Add PHP in a BLOCK

jtadeo posted 11th of July 2008 in Community Voice. 47 comments.

Extend Your Blocks with the Power of PHP!

It seems to have finally happened. You can now add PHP in a Block as of 612, but with one caveat. You have to make an entry in the PageCompose table and you have to add your PHP via phpMyAdmin. This shouln't be too hard as it's a lot easier now than before.

Here's a simple example:

The above example uses an echo function. For example:


echo "Look at me I'm the PHP!';


Here's one that uses a Flash chart and PHP. There's a few additional code that I had to write, but it's the same concept.

BoonexNerd.com - Dolphin Tutorial on How to Add PHP in a Block



So what has changed? Well take a look at this:

function getBlockCode_PHP( $iBlockID, $sContent ) {
ob_start();
eval($sContent);
return ob_get_clean();
}


The function can be found in the BxDolPageView.php file located in inc/classes. That new function was introduced in 612 and as such it will parse PHP code. Comapre that to the typical ECHO function:

function getBlockCode_Echo( $iBlockID, $sContent ) {
return $sContent;
}

Notice the ECHO function does not have the ob_start(), eval() or the ob_get_clean() function.


HOW TO ADD A PHP BLOCK
-----------------------------------------------------------------------
To add a PHP block, you have to do the following:
1. Make an entry in the PageCompose table.
2. Add your PHP Code in the "Content" field of your new block entry.
3. In the Admin, you have to make sure it's active in the page.


STEP 1 : MAKE AN ENTRY IN THE PAGECOMPOSE TABLE

-----------------------------------------------------------------------
Login to your phpMyAdmin and run this SQL INSERT statement:

INSERT INTO `PageCompose` (`ID`, `Page`, `PageWidth`, `Desc`, `Caption`, `Column`, `Order`, `Func`, `Content`, `DesignBox`, `ColWidth`, `Visible`, `MinWidth`) VALUES ('', 'index', '960px', 'PHP BLOCK', 'PHP BLOCK', 2, 2, 'PHP', 'echo "You can now have PHP in a block!";', 1, 50, 'non,memb', 0)

It will make an entry in your table with the necessary field values. The most important value is the value that we add for the field Func. It has to be "PHP". Take note that a block function is identified in the database by what it appended. For example, the name of the function we are working with is "getBlockCode_PHP". Notice the "_PHP" in the function name. That tells Dolphin to look for the record in the PageCompose table that has "PHP" as the value in the Func field. If we created a custom function called getBlockCode_TEST, then we would need a corresponding Func value in the PageCompose table of "TEST". This is how the function matches up with the value that is found the database. In our example, it will spit out the value found in the Content field. That's where the PHP code would go.


STEP 2 : ADD YOUR PHP CODE
-----------------------------------------------------------------------
Once you've made the record entry in the PageCompose table, the rest is pretty easy. Just add you PHP code in the Content field and save. Go to step 3 to get a sample of a db connection and display your memebers.


STEP 3 : ADD THE PHP BLOCK VIA THE ADMIN
-----------------------------------------------------------------------
The SQL INSERT statement provided will automatically add the PHP Block in your admin under Builders so the only thing you would need to do is move the block to where you want it to be.

****One of the quirky things about the Dolphin is how it keeps and show information. In some cases you may need to refresh the page or move a block to make sure that your changes will update. For example, moving a block to another location in the page builder will usually do it.


Below is sample PHP code that will list all your members. You can copy and paste this bit of code in the PageCompose table.

$jt_dbHost="localhost";
$jt_dbLogin="yourlogin";
$jt_dbPass="yourpass";
$jt_db="yourdb";

$connection=mysql_connect("$jt_dbHost","$jt_dbLogin","$jt_dbPass") or die("Couldn't connect to the server.");

$db=mysql_select_db("$jt_db", $connection) or die("Couldn't select a database.");

$sql="SELECT * FROM Profiles";

$sql_result=mysql_query($sql,$connection) or die("Couldn't execute query!");

echo "PROFILES LISTING:<BR>";
while($row=mysql_fetch_array($sql_result)) {
$NickName=$row["NickName"];
echo "<br>$NickName";
}

echo "<br><br><br>CONGRATS! The db connected properly.";

mysql_close($connection);

Please try it out and let me know how it goes.

...sip...

 
Comments
·Oldest
·Top
Please login to post a comment.
okweb
WORK GREAT
If you edit some code in it later, remember to move the block in admin to show your last changes on your website
jtadeo
Thanks okweb.

I have a few more advanced tutorials I am writing, if you're interested in reviewing them please let me know. Send me a PM etc and I will send you the links.
mscott
You sir are a genius, and the fact that only one person commented on this blog says a LOT about our community :-)
zankoku666
Wow this function just arrived on 6.1.2?

T_T my life is going to be easier I think Im gonna cry months and months on a learning curve with no end, thank you jtadeo...and the boonex dudes who realize that was necessary!

It worked perfectly, now Im wandering if I can include a file and then alot lots of things now can happen!!!
jtadeo
Hey guys thanks for the encouragement. I think it might be a bit too advanced for some or not too many people are interested. At any rate, I'm going to finish my basic tutorials and leave it at that.
Just so you know, you saved my butt :) I didn't know how I was going to pull this off until I came here :)

THANK YOU!
jonbrennan
Great job. In fact, you gave me the idea to try it with a 6.1.1 install. I added the function to the BxDolPageView and then added the block to the PageCompose per your tutorial which seemed very straight forward and well written. Worked without incident. Thanks!
bobp
I'm a brand new dolphin ..... so far in my very brief adventure, it seems that James provides more insight into the inner workings of Dolphin than I can find anywhere else.

James, thanks for this contribution!

I'm trying to unravel the dolphin template puzzle. If I could get a small assist with a few questions, I think I can be on my way.

For example, I'm trying to customize the Groups/Entry page (the page that displays when you click on a group that you belong to from 'my profile' page). see more I believe this involves grp.php in the top level folder, BxDolGroups.php in the inc/classes folder and page_71.html in the tmpl_uni folder.

Your example here, adding a PHP block is exactly what I need to add at the bottom of the group main display page. I understand how to create a PHP block, but how do I invoke the block from the group main display page?

In your example here, you talk about using the admin Pages Builder tool to place the PHP block on one of the pages. Which works great for pages that the tool handles. Unfortunately, the admin Pages Builder tool only manages a subset of pages including classifieds, homepage, account, shared music, shared photo, profile, and shared video.

The group display page is one of the pages that Pages Builder tool includes, so I believe I need to manipulate the appropriate template file and associated code that generates the content for the groups display page directly.

In my case, is there a way to add a reference to a custom PHP block (row in PageCompose table) in the page_71.html template? And would I need to add code to BxDolGroups.php to render? For example, in BxDolGroups, I think I would need to add code to the BxDolGroups class function 'GenGroupMainPage' that populates and returns an array of page element values?

Am I on the right track, or am I completely clueless? Can't seem to put it together.

Thanks in advance for your generous help.

Bob
bobp
I'm a brand new dolphin ..... so far in my very brief adventure, it seems that James provides more insight into the inner workings of Dolphin than I can find anywhere else.

James, thanks for this contribution!

I'm trying to unravel the dolphin template puzzle. If I could get a small assist with a few questions, I think I can be on my way.

For example, I'm trying to customize the Groups/Entry page (the page that displays when you click on a group that you belong to from 'my profile' page). see more I believe this involves grp.php in the top level folder, BxDolGroups.php in the inc/classes folder and page_71.html in the tmpl_uni folder.

Your example here, adding a PHP block is exactly what I need to add at the bottom of the group main display page. I understand how to create a PHP block, but how do I invoke the block from the group main display page?

In your example here, you talk about using the admin Pages Builder tool to place the PHP block on one of the pages. Which works great for pages that the tool handles. Unfortunately, the admin Pages Builder tool only manages a subset of pages including classifieds, homepage, account, shared music, shared photo, profile, and shared video.

The group display page is not one of the pages that Pages Builder tool includes, so I believe I need to manipulate the appropriate template file and associated code that generates the content for the groups display page directly.

In my case, is there a way to add a reference to a custom PHP block (row in PageCompose table) in the page_71.html template? And would I need to add code to BxDolGroups.php to render? For example, in BxDolGroups, I think I would need to add code to the BxDolGroups class function 'GenGroupMainPage' that populates and returns an array of page element values?

Am I on the right track, or am I completely clueless? Can't seem to put it together.

Thanks in advance for your generous help.

Bob
jtadeo
Hi bobp,

I will be updating this at my boonexnerd.com site. I am getting some help updating tutorial files etc.
bobp
yikes, sorry for the double post.

the second post has a correction - 'the group display page is not one of the pages that Pages Builder tool includes ....'

Bob
Varius
Hi,

I tried following your tutorial above, yet after doing the SQL INSERT statement and viewing it in the DB fine, nothing new appears in my Admin->Builer->Page Builder->Profile

Here is what i added to my db:

mysql> select * from PageCompose where ID=90 \G
*************************** 1. row ***************************
ID: 90
Page: profile
PageWidth: 317px
Desc: Profile Videos
Caption: Profile Videos
Column: 1
Order: 2
Func: PHP
Content: see more echo "Keith";
DesignBox: 1
ColWidth: 50
Visible: non,memb
MinWidth: 0

Any thoughts? using Dolphin 6.1.4
RumpyBumpy
Added PHP blocks and they show up in builder fine but finished page the block shows up with following inside:

Parse error: syntax error, unexpected '<' in /home/xxxxxx/public_html/dolphin/inc/classes/BxDolPageView.php(281) : eval()'d code on line 1

There is no < on line 281 in BxDolPageView.php .....
Where would I find the evaluated code to review line 1?

OR ..... what's wrong?
.
Snig
Same problem as RumpyBumpy. I added a ?> at the end of BxDolPage...php but I still get the same error.

Any ideas?
zak2008
First, I need to thank 'jtadeo' for posting his knowledge. It has worked most of it for me by following the steps given, but once I replaced the 'echo' statement in Content, I've been getting the same error as the others above:

Parse error: syntax error, unexpected '<' in /home/ethiomys/public_html/inc/classes/BxDolPageView.php(308) : eval()'d code on line 1

Anyone has a solution?
zak2008
After many trial and error, my block works fine. But it worked only because I had to remove all html and javascript codes inside the php script. I couldn't parse other scripts in the PHP Block unless its only php script.

Is there anyone with suggestion on how to get the PHP block working with php code that contains html or java codes?

Here is mine the couldn't work:

<?php
include "config.php";
include "functions.php";
?>

<script language="javascript" see more type="text/javascript">
if(top!=self)
{
top.location.href=self.location.href;
}
</script>

<div id="page">
<div id="header">
<div id="text">
<h1>Shoutbox</h1>
</div>
<div id="menu">
<a href="index.php<?php if($_SERVER['QUERY_STRING'] != ""){ echo "?" . $_SERVER['QUERY_STRING']; }?>">Refresh</a> | <a href="index.php?item=0">Shoutbox History</a> | <a href="http://code.google.com/p/freepss/">Get your own</a>
</div>
<div id="content">
<?php include"post.php"; ?>
</div>
</div>
<div id="footer">

<p class="copy">© 2006 All rights reserved.</p>
</div>
</div>
Snig
zak2008 had the answer. Once I removed the php tags from the mix the block works fine.
zak2008
Thx Snig...I forgot to post, but I did exactly what you sd, and indeed it works.
s4ns4n
I use dolphin 6.14
after reading your instructuion
i can't find PHP BLOCK in my BUILDER
what's wrong?
what version does this work with exactly? i have 6.1 so i dont want to create more problems yet.

thanks!
this is not really working, and it's so bad
melia
I tried this again and it's working fine. PHP blocks everywhere!
BoonexNerd_com
There's an update to this tutorial and new code will be released.
ygryggil
Is the new code released?
newdreamers
Thanks JTADEO. Now, ok, I just couldn't resist digging more into it, so if you want to enable PHP BLOCKS in the admin section, simply follow the 4-steps guide below.

Note: I strongly recommend you backup your BxDolPageViewAdmin.php just in case...

--------------------
STEP 1
--------------------
Run the following Insert query in the pageCompose table:

INSERT INTO `PageCompose` ( `ID` , `Page` , `PageWidth` , `Desc` , `Caption` , `Column` , `Order` , `Func` , `Content` , `DesignBox` , see more `ColWidth` , `Visible` , `MinWidth` )
VALUES (NULL , '', '960px', 'PHP Block', '_PHP Block', '0', '0', 'Sample', 'PHP', '1', '0', 'non,memb', '0');

The key field is "Func", being set to "Sample". Any record set to "Sample" in this table will make the relevant block appear among the Samples(!) in the "page builders" section. Try and look at any page from the Page Builders screen, you'll now see the PHP block displayed as Sample.

--------------------
STEP 2
--------------------

Edit the following file:
./inc/classes/BxDolPageViewAdmin.php

Update the saveItem function (starting line 174) by modifying line 187:

FROM: elseif( $sFunc == 'Echo' )
TO: elseif( $sFunc == 'Echo' or $sFunc == 'PHP' )

This will enable the PHP code to be saved from the admin interface.

--------------------
STEP 3
--------------------

Modify line 553:

FROM: if( $aItem['Func'] == 'RSS' or $aItem['Func'] == 'Echo' ) {
TO: if( $aItem['Func'] == 'RSS' or $aItem['Func'] == 'Echo' or $aItem['Func'] == 'PHP' ) {

This will enable the "Delete" button in the PHP blocks popup form

--------------------
STEP 4
--------------------

Search for :

if( $aItem['Func'] == 'Echo' )

This IF condition defines what fields to display in the block popup form, based on the block type/func. You just need to insert the following on line 533
(just before the end of the IF condition for the HTML blocks):

... etc etc...
<?
// THE INSERT STARTS HERE

} elseif( $aItem['Func'] == 'PHP' ) {
?>
<tr>
<td class="form_label">PHP-code:</td>
<td>&nbsp;</td>
</tr>
<tr>
<td class="form_colspan" colspan="2">
<textarea style="width: 450px; height: 350px;" name="Content"><?= htmlspecialchars_adv( $aItem['Content'] ) ?></textarea>
</td>
</tr>
<?

// THE INSERT FINISHES HERE
} elseif( $aItem['Func'] == 'RSS' ) {
... etc etc...

--------------------
ET VOILA!
--------------------

Now you can manage PHP blocks straight from the admin section without having to fiddle with MySQL or other geeky stuff!

Personally I can think of loads of new blocks I'm gonna create... right now actually!

Dunno what's coming up with 6.2, hope fully they'll incorporate this by default :-)

HAVE FUN!

--------------------
DISCLAIMER
--------------------
- Don't make the modif if you're not comfortable with PHP
- This "hack" might get overridden/overwritten by future releases
miskam
Hello,
can I insert a language string in to this php block?

example:
A user from UK see in this block a link with name "ocean" and the other user from Germany see "oZean".
than you
meovino
@James,

Let me start by saying that this is just a great tutorial, and @newdreamers' addition is just the icing on the cake. Just one question, is there an advantage to using a PHP block over an HTML block that does an AJAX call out to another PHP script that returns your data?

Seems like either method would get you the desired effect and the AJAX method would let the page load while the AJAX-requested data is loading. On the other hand, there may be great advantages to using the PHP block see more that I'm ignorant of, so please don't hesitate to put me in my place here.

Thanks!
Mike E.
jtadeo
meovino,

You can use Ajax with the php block no probs!

I prefer pure PHP for my blocks as it gives me more control of data should I need it in the future.

Best,
James
ladybugn
wow, melikes!

I have a bad habit of rushing to implement things that are existing in my build.. is this cool for 6.1.4?

And does anyone have any examples of how you used a php block on your site?
DiGiTaLLL
wtf ? didn't work , it writes : Parse error: syntax error, unexpected $end, expecting ',' or ';' in /var/www/html/www.watchme.lv/htdocs/inc/classes/BxDolPageView.php(281) : eval()'d code on line 1!!!
alienbee
this doesnt work in 6.1.4
jtadeo
alienbee,

It does work with 6.1.4. I have dozens of sites that make use of this technique. Check out my Dolphin site (see my profile) and you will see a Daily Quotes block that randomly generates a quote with each page refresh.

You can also check out okweb's tutorial on showing a Daily Quote and newdreamers tutorial. Both members have kindly gave their time to provide some very useful info on its usage.

Good luck!
Nicefriendd
Hi, this does not work in 6.0.03.
I want to add some php script in the Dolphin but still do not know how i may do that. Please guide me

Thanks
jtadeo
It will only work in 612 and above.

You will need to hire a programmer to make it work in the older versions.
GiMM
Hi. DiGiTaLLL,

I assume, you have started your php code inside of the new PHP Block with <?php and ended it up with ?>, am I right?

So this time skip the opening and closing brackets and leave just the php script you've written and you should be fine.

In other words instead of

<?php .....your php script..... ?>

use this:

.....your php script.....

Hope, it helped
glany222
Hi jtadeo.. ur brilliant.. atlast I found this anser for inserting php block. I dont know why dolphin doesnt have good tutorial...
meetbg
Not working for me! Used my own php code to print out SMS winners and not working, can you help me please, I`m using Dolphin 6.1.4 ?
aph3x
thank you jtadeo, it worked perfectly!
yanno
hi,

i've tried it and it waorks fine for me until i introduce the mysql_fetch.

the code is:$MySQL = new CMySQL;
$res = db_arr( "SELECT NickName FROM `Profiles`" );

echo "PROFILES LISTING:<BR>";
$row=mysql_fetch_array($res);

echo $row["NickName"];

echo "<br><br><br>CONGRATS! The db connected properly.";

and the output is:
PROFILES LISTING:

Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result see more resource in /homez.110/facecook/www/inc/classes/BxDolPageView.php(281) : eval()'d code on line 5

CONGRATS! The db connected properly.

any idea?

thanks

yanno
yanno
sorry, i've realized my mistake!
I used db_arr instead of db_res ...
jtadeo
You guys may also want to check out newdreamers addition to this PHP block tutorial. The tutorial shows you how to add it directly from your builder page. This avoid the phpmyadmin approach.

Here's the link:
http://www.boonex.com/unity/blog/entry/How_to_enable_PHP_block_in_the_Page_Builder

Hopefully it didn't get cut off, but if it did here's a tinyurl version of it:

http://tinyurl.com/newdreamer

...sip...
jtadeo
...oh nice...it did get cut off...

oh well.
ThinkArchimedes
This, sir, is entirely amazing. Can this same approach be done to use Python, Javascript, ASP, etc.?

If I want another box I guess I just insert another row?
cmpfxdesign
Great Tutorial! I myself am a self-educated Web Application Deveoper. However, I am new to dolphin. I hope to see some more tutorials from you in the future. And even start posting tutorials myself.
Thanx
CMP
ProfessorSr
OK. Here is where I am at so far. I have figured out how to create multiple form pages into a module. I also know how to create a custom page. Now, how do i get my module to display custom page.

At http://www.mytherapysession.net/m/complete/generalhealth you will see one of the pages that is displayed from my modules/mts/complete/classes/MtsCompleteModule.php

On this page there are a few functions like this:



function actionGeneralHealth () {

if (!$GLOBALS['logged']['member'] && see more !$GLOBALS['logged']['admin']) { // check access to the page
$this->_oTemplate->displayAccessDenied ();
return;
}

$this->_oTemplate->pageStart(); // all the code below will be wrapped by the user design

bx_import ('BxTemplFormView'); // import forms class

$oForm = new BxTemplFormView ($this->generalhealthForm); // create foprms class

$oForm->initChecker(); // init form checker

if ($oForm->isSubmittedAndValid ()) { // if form is submitted and not form errors were found, save form data

$aValsAdd = array ( // add additional fields
'date' => time(),
'patient_id' => $_COOKIE['memberID'],
);
$iEntryId = $oForm->insert ($aValsAdd); // insert data to database

if ($iEntryId) { // if post was successfully date
$sRedirectUrl = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $iEntryId;
header ('Location:' . $sRedirectUrl); // redirect to created post view page
exit;
} else {
MsgBox(_t('_Error Occured')); // if error occured display error message
}

} else {

echo $oForm->getCode (); // display form, if the form is not submitted or data is invalid

}

$this->_oTemplate->pageCode(_t('_mts_complete_page_title_add'), true); // output is completed, display all output above data wrapped by user design
}

//end of code



Now, If you go to mytherapysession.net/example.php - you will see a basic custom page with no blocks.



What I want to do is to use a custom page to display the form in a block so that i can add more blocks to the page.
ilynxhost
what's the php code to show featured photo? sorry very new to this
 
 
Below is the legacy version of the Boonex site, maintained for Dolphin.Pro 7.x support.
The new Dolphin solution is powered by UNA Community Management System.
PET:0.18532395362854