<?xml version="1.0" encoding="UTF-8"?><!-- generator="wordpress.com" -->
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	>

<channel>
	<title>php &amp;laquo; WordPress.com Tag Feed</title>
	<link>http://wordpress.com/tag/php/</link>
	<description>Feed of posts on WordPress.com tagged "php"</description>
	<pubDate>Tue, 07 Oct 2008 22:29:18 +0000</pubDate>

	<generator>http://wordpress.com/tags/</generator>
	<language>en</language>

<item>
<title><![CDATA[Webgrind, a Web frontend for Xdebug]]></title>
<link>http://phpimpact.wordpress.com/?p=899</link>
<pubDate>Tue, 07 Oct 2008 22:04:35 +0000</pubDate>
<dc:creator>Federico</dc:creator>
<guid>http://phpimpact.cs.wordpress.com/2008/10/07/webgrind-a-web-frontend-for-xdebug/</guid>
<description><![CDATA[Webgrind is an Xdebug profiling web frontend in PHP5. It implements a subset of the features of kcac]]></description>
<content:encoded><![CDATA[<p><a id="Webgrind" href="http://code.google.com/p/webgrind/" target="_blank">Webgrind</a> is an <a rel="nofollow" href="http://www.xdebug.org/">Xdebug</a> profiling web frontend in PHP5. It implements a subset of the features of <a rel="nofollow" href="http://kcachegrind.sourceforge.net/cgi-bin/show.cgi">kcachegrind</a> and installs in seconds and works on all platforms. For quick and dirty optimizations it does the job.</p>
<p><a href="http://phpimpact.files.wordpress.com/2008/10/webgrind_small.jpg"><img class="aligncenter size-full wp-image-902" title="webgrind_small" src="http://phpimpact.wordpress.com/files/2008/10/webgrind_small.jpg" alt="" width="440" height="324" /></a></p>
<h3>Features</h3>
<ul>
<li>Super simple, cross platform installation.</li>
<li>Track time spent in functions by self cost or inclusive cost. Inclusive cost is time inside function + calls to other functions.</li>
<li>See if time is spent in internal or user functions.</li>
<li>See where any function was called from and which functions it calls.</li>
</ul>
<h3>Installation</h3>
<ol>
<li>Download <a href="http://code.google.com/p/webgrind/" target="_blank">Webgrind</a>.</li>
<li>Unzip package to favourite path accessible by a Web server.</li>
<li>Load Webgrind in browser and start profiling.</li>
</ol>
<p><a href="http://jokke.dk/blog/2008/04/webgrind_a_web_frontend_for_xdebug" target="_blank">More info</a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Настоящих хакеров приглашают на работу]]></title>
<link>http://vit12.wordpress.com/?p=83</link>
<pubDate>Tue, 07 Oct 2008 21:22:09 +0000</pubDate>
<dc:creator>vit12</dc:creator>
<guid>http://vit12.cs.wordpress.com/2008/10/08/%d0%bd%d0%b0%d1%81%d1%82%d0%be%d1%8f%d1%89%d0%b8%d1%85-%d1%85%d0%b0%d0%ba%d0%b5%d1%80%d0%be%d0%b2-%d0%bf%d1%80%d0%b8%d0%b3%d0%bb%d0%b0%d1%88%d0%b0%d1%8e%d1%82-%d0%bd%d0%b0-%d1%80%d0%b0%d0%b1%d0%be/</guid>
<description><![CDATA[Сегодня я расскажу Вам о очень интересной вакансии Web-п]]></description>
<content:encoded><![CDATA[<p>Сегодня я расскажу Вам о очень интересной вакансии Web-программиста, которая сама отсеивает большое количество "ненужных" людей. Тест написан талантливым человеком.</p>
<p>Любой работодатель хочет принять на работу действительно полезного работника и хочет что бы тот был на все 100% отличным сотрудником. Поиски такого сотрудника занимают уйму времени и часто работодателям сложно проверить врет или нет соискатель!</p>
<p>Сегодня я расскажу Вам о том как предлагает устроиться на работу одна Санкт-Петербургская компания. Называть ее я не буду, что бы они не дай бог не подумали что я о них ;-)</p>
<p>Итак, тестовое задание состоит из исходного файла содержащего две закодированные подпрограммы =) Причем, первый код декодирует второй и после выполнения нехитрой замены(хотя ткнуть носом в то место где собака зарыта я не смогу - понял пока только идею уловки).</p>
<p>Как не трудно догадаться нужно получить расшифрованный вариант начального исходного кода!</p>
<p>Нет! А самое смешное, что если Вам удалось расшифровать код, то вы в принципе способны взломать всю систему!</p>
<p>Таким вот образом если вы Хакер автоматом зачисляют на работу!</p>
<p>Помоему просто гениально!</p>
<p><strong>UPD</strong>. Собака зарыта в очень хитрой бинарной замене символа 0x0A в исходной декодированной строке функцией strtr в переменной $_X!</p>
<p><strong>UPD2</strong>: Кстати просто гениальное решение пришло от подсказки, можно заменить во второй подпрограмме функцию <em>eval</em> на <em>print</em>.</p>
<p><strong>P.S.</strong> Если кому-то интересно пишите в коментариях свою контактную информацию - вышлю это тестовое задание!</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Ejecutando un Flash con PHP en forma remota]]></title>
<link>http://rosariomonteverde.wordpress.com/?p=36</link>
<pubDate>Tue, 07 Oct 2008 17:01:44 +0000</pubDate>
<dc:creator>rosariomonteverde</dc:creator>
<guid>http://rosariomonteverde.cs.wordpress.com/2008/10/07/ejecutando-un-flash-con-php-en-forma-remota/</guid>
<description><![CDATA[Bueno, hace un tiempo tuve el siguiente problema: un cliente tenía servidor windows, y quería desa]]></description>
<content:encoded><![CDATA[<p>Bueno, hace un tiempo tuve el siguiente problema: un cliente tenía servidor windows, y quería desarrollar una aplicacioncita para manejar sus contenidos. PHP no corría en el servidor. El workaround que encontramos fue ejecutar un flash en "forma remota" (sí! es una chanchada! pero bueno, es lo que hay, y soluciona el problema):</p>
<p>1. En nuestro HTML ponemos un Flash que va a desplegar el contenido que querramos.</p>
<p>2. Programamos el flash para que acceda a un PHP que nos va a traer los datos que querramos.</p>
<p>3. En el servidor Windows subimos el HTML, y en un servidor Linux (otro que tengamos) subimos el Flash y el PHP. El HTML levanta el flash que está en el servidor Linux (para eso ponemos la ruta absoluta donde está el flash en el HTML ej: http://www.midominiolinux.com/flashito.swf).</p>
<p><strong>ATENCIÓN:</strong> (y esto es el punto importante de este post) para que el flashito levante las cosas del PHP y funcione correctamente, <em>hay que poner la ruta absoluta del php dentro del flash </em>(ej. no alcanza con poner load (miphp.php) por más que el swf esté en la misma carpeta que el php.. hay que poner "load (http://www.midominiolinux.com/miphp.php).</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Mediawiki Skinning]]></title>
<link>http://socialcompute.wordpress.com/?p=6</link>
<pubDate>Tue, 07 Oct 2008 16:12:18 +0000</pubDate>
<dc:creator>tabasa</dc:creator>
<guid>http://socialcompute.cs.wordpress.com/2008/10/07/mediawiki-skinning/</guid>
<description><![CDATA[Mediawiki has provided an amazing way to collaborate and dramatically improve the companies knowledg]]></description>
<content:encoded><![CDATA[<p class="MsoNormal">Mediawiki has provided an amazing way to collaborate and dramatically improve the companies knowledge base, it's an open source technology and free to download <a title="media wiki download" href="http://www.mediawiki.org/wiki/Download" target="_blank">here </a>. Multimillion dollar companies are now beginning to adapt the idea of having a central collaborative site that helps their employee interact and increase awareness in the company. Welcome to the future of Enterprise Wiki a part Web 2.0, companies like Pfizer, Boeing and others are now joining the bandwagon. This is part of the social networking in the enterprise settings and benefits can be immediately recognized in using this technology.</p>
<p class="MsoNormal">So in the spirit of How-to's I am actually going to walk you through some tips on how to Skin your mediawiki to fit your company's theme.</p>
<p class="MsoNormal"><span style="font-family:&#34;">Mediawiki engine provides some great implementation on changing or customizing its skin. these pages can be customizable and can be changed provided you have enough privileges and ‘sysop’ rights. In this document we will provide instructions and “how-to’s” in customizing your mediawiki skin.</span></p>
<p class="MsoNormal"><span style="text-decoration:underline;"><span style="font-family:&#34;">Manual Skinning</span></span></p>
<p class="MsoNormal"><span style="font-family:&#34;">In preparation for manual skinning you need to decide what skins to use, Mediawiki comes with few skins during installation process, namely “Monobook” (which is the popular one) ,”Classic”, “Blue Cologne” and “Simple”. You can preview these by going to [My Preferences]-&#62; [Skins]</span></p>
<p class="MsoNormal"><span style="font-family:&#34;">What you need to do is to copy the Style that you want for instance “<em>Monobook</em>” then rename it as follows:</span></p>
<p class="MsoNormal"><span style="font-family:&#34;">Copy folder “<em>Monobook</em>” rename to something like “<em>Companypedia</em>”</span></p>
<p class="MsoNormal"><span style="font-family:&#34;">Copy file “<em>monobook.php</em>” take note that the filename is in lowercase and folder is in uppercase reason for this is that the folder is the extension of your class, you will notice later when we get to that part.</span></p>
<p class="MsoNormal"><span style="font-family:&#34;">After copying <em>monobook.php</em> re-name it to <em>companypedia.php</em> (lowercase remember?)</span></p>
<p class="MsoNormal"><span style="font-family:&#34;">Then open <em>mpedia.php </em><span> </span>using any of your favorite editor.</span></p>
<p class="MsoNormal"><span style="font-family:&#34;">Go to the following line and do the changes as follows:</span></p>
<p class="MsoNormal"><span style="font-family:&#34;">class SkinMonobook extends SkinTemplate {<span> </span><span style="color:#8db3e2;">// becomes : class SkinCompanypedia extends SkinTemplate</span></span></p>
<p class="MsoNormal"><span style="font-family:&#34;"><span> </span>/** Using monobook. */ <span style="color:#8db3e2;">//using mpedia</span></span></p>
<p class="MsoNormal"><span style="font-family:&#34;"><span> </span>function initPage( &#38;$out ) {</span></p>
<p class="MsoNormal"><span style="font-family:&#34;"><span> </span>SkinTemplate::initPage( $out );</span></p>
<p class="MsoNormal"><span style="font-family:&#34;"><span> </span>$this-&#62;skinname<span> </span>= 'monobook'; <span style="color:#8db3e2;"><span> </span>// becomes: $this-&#62;skinname=’companypedia’;</span></span></p>
<p class="MsoNormal"><span style="font-family:&#34;"><span> </span>$this-&#62;stylename = 'monobook'; <span style="color:#8db3e2;">// becomes: $this-&#62;stylename=’</span></span><span style="font-family:&#34;"><span style="color:#8db3e2;">companypedia</span></span><span style="font-family:&#34;"><span style="color:#8db3e2;">’;</span></span></p>
<p class="MsoNormal"><span style="font-family:&#34;"><span> </span>$this-&#62;template<span> </span>= 'MonobookTemplate'; <span style="color:#8db3e2;">// becomes: $this-&#62;template=’</span></span><span style="font-family:&#34;"><span style="color:#8db3e2;">companypedia</span></span><span style="font-family:&#34;"><span style="color:#8db3e2;">’;</span></span></p>
<p class="MsoNormal"><span style="font-family:&#34;"><span> </span>}</span></p>
<p class="MsoNormal"><span style="font-family:&#34;">}</span></p>
<p class="MsoNormal"><span style="font-family:&#34;">Then also do the following changes on this line:</span></p>
<p class="MsoNormal"><span style="font-family:&#34;">wfRunHooks( 'MonobookTemplateToolboxEnd', array( &#38;$this ) ); <span style="color:#8db3e2;">// becomes: CompanypediaTemplateToolBoxEnd</span></span></p>
<p class="MsoNormal"><span style="font-family:&#34;">Now the fun part…</span></p>
<p class="MsoNormal"><span style="font-family:&#34;">Once you have completed the above task, you have a new skin to switch to new skin go to your site and on the Preference-&#62; select a skin and select ‘mpedia’ as your new skin before attempting to edit the main.css so you can monitor the changes you will be making.</span></p>
<p class="MsoNormal"><span style="font-family:&#34;">The most useable parts in the CSS are the following:</span></p>
<p class="MsoNormal"><span style="font-family:&#34;">(Open your main.css under the new folder you have created ‘companypedia’)</span></p>
<p class="MsoNormal"><span style="font-family:&#34;">You normally start off with the Body { <span style="color:#e36c0a;">this helps you setup your header-image and can be set as a background</span></span></p>
<p class="MsoNormal"><span style="font-family:&#34;">#column-one { padding-top:135px;<span> </span>} <span style="color:#e36c0a;">this here is responsible for your left navigation tab making changes to ‘padding’ will bring down or up your left navigation box</span></span></p>
<p class="MsoNormal"><span style="font-family:&#34;">#content { <span style="color:#e36c0a;">this style is responsible for your middle content you can play with the bg and stuff.</span></span></p>
<p class="MsoNormal"><span style="font-family:&#34;">#globalWrapper { <span style="color:#e36c0a;">this one can set your site in the middle or left or right align and provide borders on the whole body.</span></span></p>
<p class="MsoNormal"><span style="font-family:&#34;">#p-cactions { <span style="color:#e36c0a;">this provides manipulation on the top menus such as edit, discussions , help etc.</span></span></p>
<p class="MsoNormal"><span style="font-family:&#34;">#p-personal { <span style="color:#e36c0a;">is your personal toolbar, this is the link on the right hand top corner of your site where your login information is located</span></span></p>
<p class="MsoNormal"><span style="font-family:&#34;">#p-search { <span style="color:#e36c0a;">is your search box, with the proper settings you can place this anywhere without destroying other elements in the page</span></span></p>
<p class="MsoNormal"><span style="font-family:&#34;">#p-logo { <span style="color:#e36c0a;">by playing with this settings you can increase/decrease your logo and position it according to your design</span></span></p>
<p class="MsoNormal"><span style="font-family:&#34;">.portlet<span style="color:#e36c0a;"> </span>{<span style="color:#e36c0a;"> this is element holding your menu tabs in the left navigation</span></span></p>
<p class="MsoNormal"><span style="font-family:&#34;">#footer { <span style="color:#e36c0a;">self</span><span style="color:#e36c0a;"> explanatory, this is the footer of the page</span></span></p>
<p class="MsoNormal">There you have it, it's always a good idea to back up your files whenever your working on the production site, I'm sure you know why, it's always a good practice to have a backup of the original files you are messing around with.</p>
<p class="MsoNormal">
<p class="MsoNormal">
]]></content:encoded>
</item>
<item>
<title><![CDATA[My Website]]></title>
<link>http://marinifamily.wordpress.com/?p=502</link>
<pubDate>Tue, 07 Oct 2008 16:01:01 +0000</pubDate>
<dc:creator>Timmy</dc:creator>
<guid>http://marinifamily.cs.wordpress.com/2008/10/07/my-website/</guid>
<description><![CDATA[Folks,
I own a website at www.marinifamily.org I don&#8217;t know if you are all aware. I have been ]]></description>
<content:encoded><![CDATA[<p>Folks,</p>
<p>I own a website at <a title="Marini Family.org" href="http://www.marinifamily.org">www.marinifamily.org</a> I don't know if you are all aware. I have been very neglectful in maintaining it. I have really shifted focus to this and <a title="KXRT Blog" href="http://kxrt.wordpress.com">other</a> blogs. I also keep up on <a title="Twitter" href="http://twitter.com/timmywa">Twitter</a> and <a title="My Facebook" href="http://www.facebook.com/profile.php?id=589574973&#38;ref=name">Facebook</a> and even a small amount of time on <a title="My MySpace" href="http://www.myspace.com/timmywa123">MySpace</a>. I love my old webpage and it offers freedoms that these others lack. I can have advertising and javascript apps that Wordpress rules out.</p>
<p>At this point, I am facing some decisions as to what the future of my webpage should be. I feel like I can communicate better through blogging. I feel like more of you can be exposed to my life and thoughts in a more narrative fashion. Blogging is very easy and powerful. I've seen it cause a great deal of change. It's stirred up plenty of heated debate and discussion that otherwise wouldn't be possible on a normal webpage.</p>
<p>I keep renewing my domain each year and don't plan to let it expire. I am grateful for David's server space and support. I would like to learn more about HTML, XML, PHP and such things.</p>
<p>My purpose in writing this is to just have you all go take a peak, see what there is to see and come back and comment here. What are some good ideas that I can work on. It's an open canvas. Thanks in advance for your help.</p>
<p>-Timmy</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[PDO (PHP Data Objects)]]></title>
<link>http://actualtraining.wordpress.com/2008/10/07/pdo-php-data-objects/</link>
<pubDate>Tue, 07 Oct 2008 14:11:42 +0000</pubDate>
<dc:creator>Erick Kurniawan</dc:creator>
<guid>http://actualtraining.cs.wordpress.com/2008/10/07/pdo-php-data-objects/</guid>
<description><![CDATA[
PDO Introduction 
PDO (PHP Data Objects) adalah salah satu ekstensi yang disupport oleh PHP5 untuk ]]></description>
<content:encoded><![CDATA[</p>
<h4>PDO Introduction </h4>
<p>PDO (PHP Data Objects) adalah salah satu ekstensi yang disupport oleh PHP5 untuk mendefinisikan lightweight DBMS connection abstraction library atau dapat juga disebut database abstraction library. PDO digunakan untuk melakukan koneksi dengan berbagai macam database yang di support oleh PHP.
<p>Jika anda pernah menggunakan PHP dan database MySQL anda pasti pernah menggunakan perintah-perintah sebagai berikut:
<div>
<pre style="font-size:8pt;overflow:visible;width:100%;color:black;line-height:12pt;font-family:consolas, 'Courier New', courier, monospace;background-color:#f4f4f4;border-style:none;margin:0;padding:0;">mysql_connect($host, $user, $password);
mysql_select_db($db);
</pre>
</div>
<p>Atau ketika anda menggunakan PHP dan database SQL Lite maka anda menggunakan perintah: </p>
<div>
<pre style="font-size:8pt;overflow:visible;width:100%;color:black;line-height:12pt;font-family:consolas, 'Courier New', courier, monospace;background-color:#f4f4f4;border-style:none;margin:0;padding:0;">$dbh = sqlite_open($db, 0666);</pre>
</div>
<p>Dengan menggunakan perintah-perintah tersebut diatas maka aplikasi yang anda buat akan terikat dengan database yang anda gunakan secara spesifik. Ketika anda akan melakukan migrasi database maka anda harus merubah seluruh script anda, dan hal ini akan sangat menyulitkan anda. </p>
<p>PDO menawarkan cara yang berbeda untuk bekerja dengan database secara lebih umum, dengan PDO perintah yang anda tuliskan untuk koneksi dengan database MySQL, SQLite, dan Postgree adalah sebagai berikut: </p>
<div>
<pre style="font-size:8pt;overflow:visible;width:100%;color:black;line-height:12pt;font-family:consolas, 'Courier New', courier, monospace;background-color:#f4f4f4;border-style:none;margin:0;padding:0;"><span style="color:#008000;">// For MySQL:</span>
$conn = <span style="color:#0000ff;">new</span> PDO(<span style="color:#006080;">"mysql:host=$host;dbname=$db"</span>, $user, $pass);
<span style="color:#008000;">// For SQLite:</span>
$conn = <span style="color:#0000ff;">new</span> PDO(<span style="color:#006080;">"sqlite:$db"</span>);
<span style="color:#008000;">// And for PostgreSQL:</span>
$conn = <span style="color:#0000ff;">new</span> PDO(<span style="color:#006080;">"pgsql:host=$host dbname=$db"</span>, $user, $pass);
</pre>
</div>
<p>Dengan PDO anda akan tidak perlu mengganti kode yang sudah anda buat sebelumnya ketika akan melakukan migrasi program. </p>
<p>Pada tutorial dibawah ini penulis akan menunjukan bagaimana cara bekerja dengan database menggunakan PDO. </p>
<h4>Database Sample</h4>
<p>Buat sample database yang akan digunakan pada aplikasi contoh, pertama buat database dengan nama <strong>pdo</strong> kemudian buat dua table dengan nama <strong>books</strong> dan <strong>authors</strong> </p>
<div>
<pre style="font-size:8pt;overflow:visible;width:100%;color:black;line-height:12pt;font-family:consolas, 'Courier New', courier, monospace;background-color:#f4f4f4;border-style:none;margin:0;padding:0;">mysql&#62; <span style="color:#0000ff;">create</span> <span style="color:#0000ff;">database</span> pdo;
Query OK, 1 <span style="color:#0000ff;">row</span> affected (0.05 sec)
mysql&#62; <span style="color:#0000ff;">use</span> pdo;
<span style="color:#0000ff;">Database</span> changed
mysql&#62; <span style="color:#0000ff;">create</span> <span style="color:#0000ff;">table</span> books(
    -&#62; id <span style="color:#0000ff;">int</span> <span style="color:#0000ff;">primary</span> <span style="color:#0000ff;">key</span> <span style="color:#0000ff;">not</span> <span style="color:#0000ff;">null</span> auto_increment
    -&#62; author <span style="color:#0000ff;">int</span> <span style="color:#0000ff;">not</span> <span style="color:#0000ff;">null</span>,
    -&#62; title <span style="color:#0000ff;">varchar</span>(70) <span style="color:#0000ff;">not</span> <span style="color:#0000ff;">null</span>,
    -&#62; isbn <span style="color:#0000ff;">varchar</span>(20),
    -&#62; publisher <span style="color:#0000ff;">varchar</span>(30) <span style="color:#0000ff;">not</span> <span style="color:#0000ff;">null</span>,
    -&#62; <span style="color:#0000ff;">year</span> <span style="color:#0000ff;">int</span>(4) <span style="color:#0000ff;">not</span> <span style="color:#0000ff;">null</span>,
    -&#62; summary text(2048));
Query OK, 0 <span style="color:#0000ff;">rows</span> affected (0.17 sec)
mysql&#62; <span style="color:#0000ff;">create</span> <span style="color:#0000ff;">table</span> authors(
    -&#62; id <span style="color:#0000ff;">int</span> <span style="color:#0000ff;">primary</span> <span style="color:#0000ff;">key</span> <span style="color:#0000ff;">not</span> <span style="color:#0000ff;">null</span> auto_increment
    -&#62; firstName <span style="color:#0000ff;">varchar</span>(30) <span style="color:#0000ff;">not</span> <span style="color:#0000ff;">null</span>,
    -&#62; lastName <span style="color:#0000ff;">varchar</span>(40) <span style="color:#0000ff;">not</span> <span style="color:#0000ff;">null</span>,
    -&#62; bio text(2048));
Query OK, 0 <span style="color:#0000ff;">rows</span> affected (0.00 sec)
</pre>
</div>
<p>Tambahkan record kedalam table author sebagai berikut: </p>
<div>
<pre style="font-size:8pt;overflow:visible;width:100%;color:black;line-height:12pt;font-family:consolas, 'Courier New', courier, monospace;background-color:#f4f4f4;border-style:none;margin:0;padding:0;">mysql&#62; insert <span style="color:#0000ff;">into</span> authors(firstName, lastName, bio) <span style="color:#0000ff;">values</span>(
     -&#62; <span style="color:#006080;">'Marc'</span>, <span style="color:#006080;">'Delisle'</span>, <span style="color:#006080;">'Marc Delisle is a member of the MySQL
Developers Guide'</span>);
Query OK, 1 <span style="color:#0000ff;">row</span> affected (0.14 sec)
mysql&#62; insert <span style="color:#0000ff;">into</span> authors(firstName, lastName, bio) <span style="color:#0000ff;">values</span>(
     -&#62; <span style="color:#006080;">'Sohail'</span>, <span style="color:#006080;">'Salehi'</span>, <span style="color:#006080;">'In recent years, Sohail has contributed
to over 20 books, mainly in programming and computer graphics'</span>);
Query OK, 1 <span style="color:#0000ff;">row</span> affected (0.00 sec)
mysql&#62; insert <span style="color:#0000ff;">into</span> authors(firstName, lastName, bio) <span style="color:#0000ff;">values</span>(
     -&#62; <span style="color:#006080;">'Cameron'</span>, <span style="color:#006080;">'Cooper'</span>, <span style="color:#006080;">'J. Cameron Cooper has been playing
around on the web since there was not much of a web with which to
play around'</span>);
Query OK, 1 <span style="color:#0000ff;">row</span> affected (0.00 sec)
</pre>
</div>
<p>Jika anda select semua data pada table authors maka dapt dilihat recordnya sebagai berikut: </p>
<div>
<pre style="font-size:8pt;overflow:visible;width:100%;color:black;line-height:12pt;font-family:consolas, 'Courier New', courier, monospace;background-color:#f4f4f4;border-style:none;margin:0;padding:0;">mysql&#62; <span style="color:#0000ff;">select</span> id, firstName, lastName <span style="color:#0000ff;">from</span> authors;
+----+-----------+----------+
&#124; id &#124; firstName &#124; lastName &#124;
+----+-----------+----------+
&#124;  1 &#124; Marc      &#124; Delisle  &#124;
&#124;  2 &#124; Sohail    &#124; Salehi   &#124;
&#124;  3 &#124; Cameron   &#124; Cooper   &#124;
+----+-----------+----------+
3 <span style="color:#0000ff;">rows</span> <span style="color:#0000ff;">in</span> <span style="color:#0000ff;">set</span> (0.03 sec)
</pre>
</div>
<p>Tambahkan record pada table books sebagai berikut:</p>
<div>
<pre style="font-size:8pt;overflow:visible;width:100%;color:black;line-height:12pt;font-family:consolas, 'Courier New', courier, monospace;background-color:#f4f4f4;border-style:none;margin:0;padding:0;">mysql&#62; insert <span style="color:#0000ff;">into</span> books(author, title, isbn, publisher, <span style="color:#0000ff;">year</span>,
summary) <span style="color:#0000ff;">values</span>(
     -&#62; 1, <span style="color:#006080;">'Creating your MySQL Database: Practical Design Tips and
Techniques'</span>, <span style="color:#006080;">'1904811302'</span>, <span style="color:#006080;">'Packt Publishing Ltd'</span>, <span style="color:#006080;">'2006'</span>,
     -&#62; <span style="color:#006080;">'A short guide for everyone on how to structure your data and
set-up your MySQL database tables efficiently and easily.'</span>);
Query OK, 1 <span style="color:#0000ff;">row</span> affected (0.00 sec)
mysql&#62; insert <span style="color:#0000ff;">into</span> books(author, title, isbn, publisher, <span style="color:#0000ff;">year</span>,
summary) <span style="color:#0000ff;">values</span>(
     -&#62; 2, <span style="color:#006080;">'ImageMagick Tricks'</span>, <span style="color:#006080;">'1904811868'</span>, <span style="color:#006080;">'Packt Publishing
Ltd'</span>, <span style="color:#006080;">'2006'</span>,
     -&#62; <span style="color:#006080;">'Unleash the power of ImageMagick with this fast, friendly
tutorial, and tips guide'</span>);
Query OK, 1 <span style="color:#0000ff;">row</span> affected (0.02 sec)
mysql&#62; insert <span style="color:#0000ff;">into</span> books(author, title, isbn, publisher, <span style="color:#0000ff;">year</span>,
summary) <span style="color:#0000ff;">values</span>(
     -&#62; 3, <span style="color:#006080;">'Building Websites with Plone'</span>, <span style="color:#006080;">'1904811027'</span>, <span style="color:#006080;">'Packt
Publishing Ltd'</span>, <span style="color:#006080;">'2004'</span>,
     -&#62; <span style="color:#006080;">'An in-depth and comprehensive guide to the Plone content
management system'</span>);
Query OK, 1 <span style="color:#0000ff;">row</span> affected (0.00 sec)
</pre>
</div>
<h4>Mendesain Kode</h4>
<p>Desain arsitektur aplikasi yang baik adalah salah satu kunci membangun aplikasi selain desain data model yang benar. Pada contoh aplikasi yang akan dibuat kali ini, pertama anda harus membuat file untuk koneksi dengan database yang akan dipanggil disetiap file yang membutuhkan koneksi dengan database. </p>
<p>Pertama buat file dengan nama common.inc.php yang akan berisi kode untuk koneksi dengan database. Kemudian tuliskan kodenya sebagai berikut: </p>
<div>
<pre style="font-size:8pt;overflow:visible;width:100%;color:black;line-height:12pt;font-family:consolas, 'Courier New', courier, monospace;background-color:#f4f4f4;border-style:none;margin:0;padding:0;">&#60;?php
<span style="color:#008000;">/**</span>
<span style="color:#008000;"> *File untuk koneksi </span>
<span style="color:#008000;"> */</span>
<span style="color:#008000;">//dbconnection string dan username/password</span>
$connStr=<span style="color:#006080;">"mysql:host=localhost;dbname=pdo"</span>;
$user=<span style="color:#006080;">"root"</span>;
$pass=<span style="color:#006080;">""</span>;

function showHeader($title){
?&#62;
  &#60;html&#62;
  &#60;head&#62;&#60;title&#62;&#60;?=htmlspecialchars($title)?&#62;&#60;/title&#62;&#60;/head&#62;
  &#60;body&#62;
  &#60;h1&#62;&#60;?=htmlspecialchars($title)?&#62;&#60;/h1&#62;
  &#60;a href=<span style="color:#006080;">"books.php"</span>&#62;Books&#60;/a&#62;
  &#60;a href=<span style="color:#006080;">"authors.php"</span>&#62;Authors&#60;/a&#62;
  &#60;hr/&#62;
&#60;?php
}

function showFooter(){
?&#62;
  &#60;/body&#62;
  &#60;/html&#62;
&#60;?php
}

<span style="color:#008000;">//membuat connection object</span>
$conn = <span style="color:#0000ff;">new</span> PDO($connStr,$user,$pass);
?&#62;
</pre>
</div>
<p>Untuk menampilkan data yang ada pada table books buat file <strong>books.php</strong>, kemudian ketikan kode berikut:</p>
<div>
<pre style="font-size:8pt;overflow:visible;width:100%;color:black;line-height:12pt;font-family:consolas, 'Courier New', courier, monospace;background-color:#f4f4f4;border-style:none;margin:0;padding:0;">&#60;?php
include_once <span style="color:#006080;">'common.inc..php'</span>;

$q = $conn-&#62;query(<span style="color:#006080;">"select * from books order by title"</span>);

showHeader(<span style="color:#006080;">'Books'</span>);
?&#62;
&#60;table width=<span style="color:#006080;">"100%"</span> border=<span style="color:#006080;">"1"</span> cellpadding=<span style="color:#006080;">"3"</span>&#62;
&#60;tr style=<span style="color:#006080;">"font-weight: bold"</span>&#62;
  &#60;td&#62;Title&#60;/td&#62;
  &#60;td&#62;ISBN&#60;/td&#62;
  &#60;td&#62;Publisher&#60;/td&#62;
  &#60;td&#62;Year&#60;/td&#62;
  &#60;td&#62;Summary&#60;/td&#62;
&#60;/tr&#62;
&#60;?php
<span style="color:#0000ff;">while</span>($r=$q-&#62;fetch(PDO::FETCH_ASSOC)){
?&#62;
  &#60;tr&#62;
    &#60;td&#62;&#60;?=htmlspecialchars($r[<span style="color:#006080;">'title'</span>])?&#62;&#60;/td&#62;
    &#60;td&#62;&#60;?=htmlspecialchars($r[<span style="color:#006080;">'isbn'</span>])?&#62;&#60;/td&#62;
    &#60;td&#62;&#60;?=htmlspecialchars($r[<span style="color:#006080;">'publisher'</span>])?&#62;&#60;/td&#62;
    &#60;td&#62;&#60;?=htmlspecialchars($r[<span style="color:#006080;">'year'</span>])?&#62;&#60;/td&#62;
    &#60;td&#62;&#60;?=htmlspecialchars($r[<span style="color:#006080;">'summary'</span>])?&#62;&#60;/td&#62;
  &#60;/tr&#62;
&#60;?php
}
?&#62;
&#60;/table&#62;
&#60;?php
    showFooter();
?&#62;
</pre>
</div>
<p>Jika dijalankan maka tampilannya adalah sebagai berikut : </p>
<p><a href="http://www2.ukdw.ac.id/kuliah/si/erickblog/PDOPHPDataObjects_1370F/image.png"><img style="border-width:0;" height="257" alt="image" src="http://www2.ukdw.ac.id/kuliah/si/erickblog/PDOPHPDataObjects_1370F/image_thumb.png" width="754" border="0"></a> </p>
<p>Untuk menampilkan data pada table author buat halaman dengan nama authors.php, kemudian ketik kodenya sebagai berikut: </p>
<div>
<pre style="font-size:8pt;overflow:visible;width:100%;color:black;line-height:12pt;font-family:consolas, 'Courier New', courier, monospace;background-color:#f4f4f4;border-style:none;margin:0;padding:0;">&#60;?php
include_once <span style="color:#006080;">'common.inc.php'</span>;
$q=$conn-&#62;query(<span style="color:#006080;">"select * from authors order by lastname,firstname"</span>);
showHeader(<span style="color:#006080;">'Authors'</span>);
?&#62;
&#60;table width=<span style="color:#006080;">"100%"</span> border=<span style="color:#006080;">"1"</span> cellpadding=<span style="color:#006080;">"3"</span>&#62;
&#60;tr style=<span style="color:#006080;">"font-weight: bold"</span>&#62;
  &#60;td&#62;First Name&#60;/td&#62;
  &#60;td&#62;Last Name&#60;/td&#62;
  &#60;td&#62;Bio&#60;/td&#62;
&#60;/tr&#62;
&#60;?php
    <span style="color:#0000ff;">while</span>($r=$q-&#62;fetch(PDO::FETCH_ASSOC)){
?&#62;
    &#60;tr&#62;
        &#60;td&#62;&#60;?=htmlspecialchars($r[<span style="color:#006080;">'firstName'</span>])?&#62;&#60;/td&#62;
        &#60;td&#62;&#60;?=htmlspecialchars($r[<span style="color:#006080;">'lastName'</span>])?&#62;&#60;/td&#62;
        &#60;td&#62;&#60;?=htmlspecialchars($r[<span style="color:#006080;">'bio'</span>])?&#62;&#60;/td&#62;
      &#60;/tr&#62;
&#60;?
    }
?&#62;
&#60;/table&#62;
&#60;?php
    showFooter();
?&#62;
</pre>
</div>
<p><a href="http://www2.ukdw.ac.id/kuliah/si/erickblog/PDOPHPDataObjects_1370F/image_3.png"><img style="border-width:0;" height="171" alt="image" src="http://www2.ukdw.ac.id/kuliah/si/erickblog/PDOPHPDataObjects_1370F/image_thumb_3.png" width="604" border="0"></a> </p>
<h5><strong></strong>&#160;</h5>
<h5><strong>Menggunakan Parameter untuk menampilkan Author</strong></h5>
<p>Pada contoh dibawah ini akan ditunjukan bagaimana cara untuk menggunakan parameter yang dikirimkan lewat url (query string). Buat file dengan nama authordetails.php kemudian tulis kode berikut: </p>
<div>
<pre style="font-size:8pt;overflow:visible;width:100%;color:black;line-height:12pt;font-family:consolas, 'Courier New', courier, monospace;background-color:#f4f4f4;border-style:none;margin:0;padding:0;">&#60;?php
include_once(<span style="color:#006080;">'common.inc.php'</span>);

$id = $_REQUEST[<span style="color:#006080;">'id'</span>];
$q = $conn-&#62;query(<span style="color:#006080;">"select * from authors where id=$id"</span>);
$author = $q-&#62;fetch(PDO::FETCH_ASSOC);
$q-&#62;closeCursor();

<span style="color:#0000ff;">if</span>(!$author){
    showHeader(<span style="color:#006080;">'Error'</span>);
    echo <span style="color:#006080;">"Salah memasukan id author"</span>;
    showFooter();
    exit;
}
showHeader(<span style="color:#006080;">"Author: $author[firstName] $author[lastName]"</span>);
$q = $conn-&#62;query(<span style="color:#006080;">"select * from books where author=$id order by title"</span>);
$q-&#62;setFetchMode(PDO::FETCH_ASSOC);

?&#62;
&#60;h2&#62;Author&#60;/h2&#62;
&#60;table width=<span style="color:#006080;">"60%"</span> border=<span style="color:#006080;">"1"</span> cellpadding=<span style="color:#006080;">"3"</span>&#62;
&#60;tr&#62;
  &#60;td&#62;&#60;b&#62;First Name&#60;/b&#62;&#60;/td&#62;
    &#60;td&#62;&#60;?=htmlspecialchars($author[<span style="color:#006080;">'firstName'</span>])?&#62;&#60;/td&#62;
&#60;/tr&#62;
&#60;tr&#62;
  &#60;td&#62;&#60;b&#62;Last Name&#60;/b&#62;&#60;/td&#62;
  &#60;td&#62;&#60;?=htmlspecialchars($author[<span style="color:#006080;">'lastName'</span>])?&#62;&#60;/td&#62;
&#60;/tr&#62;
&#60;tr&#62;
  &#60;td&#62;&#60;b&#62;Bio&#60;/b&#62;&#60;/td&#62;
  &#60;td&#62;&#60;?=htmlspecialchars($author[<span style="color:#006080;">'bio'</span>])?&#62;&#60;/td&#62;
&#60;/tr&#62;
&#60;/table&#62;

&#60;h2&#62;Books&#60;/h2&#62;
&#60;table width=<span style="color:#006080;">"100%"</span> border=<span style="color:#006080;">"1"</span> cellpadding=<span style="color:#006080;">"3"</span>&#62;
&#60;tr style=<span style="color:#006080;">"font-weight: bold"</span>&#62;
  &#60;td&#62;Title&#60;/td&#62;
  &#60;td&#62;ISBN&#60;/td&#62;
  &#60;td&#62;Publisher&#60;/td&#62;
  &#60;td&#62;Year&#60;/td&#62;
  &#60;td&#62;Summary&#60;/td&#62;
&#60;/tr&#62;

&#60;?php
<span style="color:#0000ff;">while</span>($r=$q-&#62;fetch()){
?&#62;
&#60;tr&#62;
      &#60;td&#62;&#60;?=htmlspecialchars($r[<span style="color:#006080;">'title'</span>])?&#62;&#60;/td&#62;
      &#60;td&#62;&#60;?=htmlspecialchars($r[<span style="color:#006080;">'isbn'</span>])?&#62;&#60;/td&#62;
      &#60;td&#62;&#60;?=htmlspecialchars($r[<span style="color:#006080;">'publisher'</span>])?&#62;&#60;/td&#62;
      &#60;td&#62;&#60;?=htmlspecialchars($r[<span style="color:#006080;">'year'</span>])?&#62;&#60;/td&#62;
      &#60;td&#62;&#60;?=htmlspecialchars($r[<span style="color:#006080;">'summary'</span>])?&#62;&#60;/td&#62;
&#60;/tr&#62;
&#60;?php
}
?&#62;
&#60;/table&#62;
&#60;?php
showFooter();
?&#62;
</pre>
</div>
<p>Jalankan dengan menuliskan alamat url <a href="http://localhost/authordetails.php?id=2">http://localhost/authordetails.php?id=2</a>, anda dapat melihat hasil tampilan sebagai berikut:<a href="http://www2.ukdw.ac.id/kuliah/si/erickblog/PDOPHPDataObjects_1370F/image_4.png"><img style="border-width:0;" height="244" alt="image" src="http://www2.ukdw.ac.id/kuliah/si/erickblog/PDOPHPDataObjects_1370F/image_thumb_4.png" width="604" border="0"></a> </p>
<p>Jika id yang anda masukan tidak ada misal: <a href="http://localhost/authordetails.php?id=99">http://localhost/authordetails.php?id=99</a> maka akan muncul halaman error-nya </p>
<p><a href="http://www2.ukdw.ac.id/kuliah/si/erickblog/PDOPHPDataObjects_1370F/image_5.png"><img style="border-width:0;" height="127" alt="image" src="http://www2.ukdw.ac.id/kuliah/si/erickblog/PDOPHPDataObjects_1370F/image_thumb_5.png" width="504" border="0"></a> </p>
<p><!--more--></p>
<h5><strong>Menggabungkan Dua Table</strong></h5>
<p>Pada contoh dibawah ini akan digabungkan dua table yaitu books dan authors, kemudian ketika user memilih daftar author yang ada maka detail author akan ditampilkan. </p>
<p>&#160;</p>
<div>
<pre style="font-size:8pt;overflow:visible;width:100%;color:black;line-height:12pt;font-family:consolas, 'Courier New', courier, monospace;background-color:#f4f4f4;border-style:none;margin:0;padding:0;">&#60;?php
include_once(<span style="color:#006080;">'common.inc.php'</span>);

$q = $conn-&#62;query(<span style="color:#006080;">"SELECT authors.id, firstName, lastName, books.*
                   FROM authors, books WHERE author=authors.id ORDER BY title"</span>);
$q-&#62;setFetchMode(PDO::FETCH_NUM);
showHeader(<span style="color:#006080;">'Books'</span>);
?&#62;
&#60;table width=<span style="color:#006080;">"100%"</span> border=<span style="color:#006080;">"1"</span> cellpadding=<span style="color:#006080;">"3"</span>&#62;
&#60;tr style=<span style="color:#006080;">"font-weight: bold"</span>&#62;
  &#60;td&#62;Author&#60;/td&#62;
  &#60;td&#62;Title&#60;/td&#62;
  &#60;td&#62;ISBN&#60;/td&#62;
  &#60;td&#62;Publisher&#60;/td&#62;
  &#60;td&#62;Year&#60;/td&#62;
  &#60;td&#62;Summary&#60;/td&#62;
&#60;/tr&#62;
&#60;?php
<span style="color:#0000ff;">while</span>($r=$q-&#62;fetch()){
?&#62;
&#60;tr&#62;
    &#60;td&#62;&#60;a href=<span style="color:#006080;">"authordetails.php?id=&#60;?=$r[0]?&#62;"</span>&#62;
    &#60;?=htmlspecialchars(<span style="color:#006080;">"$r[1] $r[2]"</span>)?&#62;&#60;/a&#62;&#60;/td&#62;
    &#60;td&#62;&#60;?=htmlspecialchars($r[5])?&#62;&#60;/td&#62;
    &#60;td&#62;&#60;?=htmlspecialchars($r[6])?&#62;&#60;/td&#62;
    &#60;td&#62;&#60;?=htmlspecialchars($r[7])?&#62;&#60;/td&#62;
    &#60;td&#62;&#60;?=htmlspecialchars($r[8])?&#62;&#60;/td&#62;
     &#60;td&#62;&#60;?=htmlspecialchars($r[9])?&#62;&#60;/td&#62;
&#60;/tr&#62;
&#60;?php
}
?&#62;
&#60;/table&#62;
&#60;?php
    showFooter();
?&#62;
</pre>
</div>
<p><a href="http://www2.ukdw.ac.id/kuliah/si/erickblog/PDOPHPDataObjects_1370F/image_6.png"><img style="border-width:0;" height="170" alt="image" src="http://www2.ukdw.ac.id/kuliah/si/erickblog/PDOPHPDataObjects_1370F/image_thumb_6.png" width="604" border="0"></a> </p>
<h4>Error Handling</h4>
<p>PHP5 mempunyai fasilitas try..catch untuk menangani error yang terjadi, dengan PDO anda juga dapat menangkap error yang dapat terjadi, sebagai contoh tambahkan kode berikut pada file <strong>common.inc.php</strong>. </p>
<div>
<pre style="font-size:8pt;overflow:visible;width:100%;color:black;line-height:12pt;font-family:consolas, 'Courier New', courier, monospace;background-color:#f4f4f4;border-style:none;margin:0;padding:0;">&#60;?
function showError($message){
    echo<span style="color:#006080;">"&#60;h2&#62;Error&#60;/h2&#62;"</span>;
    echo <span style="color:#006080;">"&#60;p&#62;"</span>.htmlspecialchars($message).<span style="color:#006080;">"&#60;/p&#62;"</span>;
    showFooter();
    exit;
}
<span style="color:#008000;">//membuat connection object</span>
<span style="color:#0000ff;">try</span>
{
    $conn = <span style="color:#0000ff;">new</span> PDO($connStr,$user,$pass);
    $conn-&#62;setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}
<span style="color:#0000ff;">catch</span>(PDOException $e)
{
    showHeader(<span style="color:#006080;">'Error'</span>);
    showError(<span style="color:#006080;">"Maaf, error ditemukan.. koneksi gagal.. \n"</span> . $e-&#62;getMessage());
}
?&#62;
</pre>
</div>
<p>Jika terjadi error maka akan tampil halaman sebagai berikut: </p>
<p><a href="http://www2.ukdw.ac.id/kuliah/si/erickblog/PDOPHPDataObjects_1370F/image_7.png"><img style="border-width:0;" height="181" alt="image" src="http://www2.ukdw.ac.id/kuliah/si/erickblog/PDOPHPDataObjects_1370F/image_thumb_7.png" width="504" border="0"></a> </p>
<h4>&#160;</h4>
<h4>Membuat Fasilitas Edit Books</h4>
<p>Sekarang kita akan menambahkan fasilitas untuk mengedit data pada table books, buat file dengan nama editbook.php. sebelum menambahkan kode program tambahkan dulu index pada field isbn pada table books, karena field isbn tidak boleh diisi dengan nilai yang sama. </p>
<div>
<pre style="font-size:8pt;overflow:visible;width:100%;color:black;line-height:12pt;font-family:consolas, 'Courier New', courier, monospace;background-color:#f4f4f4;border-style:none;margin:0;padding:0;"><span style="color:#0000ff;">CREATE</span> <span style="color:#0000ff;">UNIQUE</span> <span style="color:#0000ff;">INDEX</span> idx_isbn <span style="color:#0000ff;">ON</span> books(isbn);</pre>
</div>
<p>Kemudian ketik kode berikut pada file <strong>editbook.php</strong> </p>
<div>
<pre style="font-size:8pt;overflow:visible;width:100%;color:black;line-height:12pt;font-family:consolas, 'Courier New', courier, monospace;background-color:#f4f4f4;border-style:none;margin:0;padding:0;">&#60;?php
include_once(<span style="color:#006080;">'common.inc.php'</span>);

<span style="color:#008000;">//ambil id buku</span>
$id = (<span style="color:#0000ff;">int</span>)$_REQUEST[<span style="color:#006080;">'book'</span>];
<span style="color:#0000ff;">if</span>($id){
    $q = $conn-&#62;query(<span style="color:#006080;">"select * from books where id=$id"</span>);
    $book = $q-&#62;fetch(PDO::FETCH_ASSOC);
    $q-&#62;closeCursor();
    $q=<span style="color:#0000ff;">null</span>;
}
<span style="color:#0000ff;">else</span>{
    <span style="color:#008000;">//membuat buku baru</span>
    $book=array();
}

<span style="color:#008000;">//membuat list dari author</span>
$author = array();
$q = $conn-&#62;query(<span style="color:#006080;">"SELECT id, lastName, firstName FROM authors ORDER BY lastName, firstName"</span>);
$q-&#62;setFetchMode(PDO::FETCH_ASSOC);
<span style="color:#0000ff;">while</span>($a=$q-&#62;fetch()){
    $authors[$a[<span style="color:#006080;">'id'</span>]]=<span style="color:#006080;">"$a[lastName], $a[firstName]"</span>;
}

<span style="color:#0000ff;">if</span>($_POST[<span style="color:#006080;">'submit'</span>]) {
      <span style="color:#008000;">// memvalidasi setiap field</span>
      $warnings = array();
      <span style="color:#008000;">//title </span>
      <span style="color:#0000ff;">if</span>(!$_POST[<span style="color:#006080;">'title'</span>])
    {
        $warnings[] = <span style="color:#006080;">'Silahkan menginputkan book title'</span>;
    }
    <span style="color:#008000;">// Author harus ada dalam key pada $authors array</span>
      <span style="color:#0000ff;">if</span>(!array_key_exists($_POST[<span style="color:#006080;">'author'</span>], $authors))
      {
        $warnings[] = <span style="color:#006080;">'Silahkan memilih author yang mengarang buku'</span>;
      }
      <span style="color:#008000;">// ISBN harus berupa 10-digit number</span>
      <span style="color:#0000ff;">if</span>(!preg_match(<span style="color:#006080;">'~^\d{10}$~'</span>, $_POST[<span style="color:#006080;">'isbn'</span>])) {
        $warnings[] = <span style="color:#006080;">'ISBN harus 10 digits'</span>;
      }
      <span style="color:#008000;">// Published tidak boleh kosong</span>
      <span style="color:#0000ff;">if</span>(!$_POST[<span style="color:#006080;">'publisher'</span>]) {
        $warnings[] = <span style="color:#006080;">'Silahkan masukan publisher'</span>;
      }
      <span style="color:#008000;">// Year harus 4 digits</span>
      <span style="color:#0000ff;">if</span>(!preg_match(<span style="color:#006080;">'~^\d{4}$~'</span>, $_POST[<span style="color:#006080;">'year'</span>])) {
        $warnings[] = <span style="color:#006080;">'Year harus 4 digits'</span>;
      }
      <span style="color:#008000;">// Sumary tidak boleh kosong</span>
      <span style="color:#0000ff;">if</span>(!$_POST[<span style="color:#006080;">'summary'</span>]) {
        $warnings[] = <span style="color:#006080;">'Silahkan masukan summary'</span>;
      }

      <span style="color:#008000;">//jika tidak ada error</span>
      <span style="color:#0000ff;">if</span>(count($warnings) == 0) {
        <span style="color:#0000ff;">if</span>(@$book[<span style="color:#006080;">'id'</span>]) {
              $sql = <span style="color:#006080;">"UPDATE books SET title="</span> . $conn&#62;quote($_POST[<span style="color:#006080;">'title'</span>]) .
            <span style="color:#006080;">', author='</span> . $conn-&#62;quote($_POST[<span style="color:#006080;">'author'</span>]) .
            <span style="color:#006080;">', isbn='</span> . $conn-&#62;quote($_POST[<span style="color:#006080;">'isbn'</span>]) .
            <span style="color:#006080;">', publisher='</span> . $conn-&#62;quote($_POST[<span style="color:#006080;">'publisher'</span>]) .
            <span style="color:#006080;">', year='</span> . $conn-&#62;quote($_POST[<span style="color:#006080;">'year'</span>]) .
            <span style="color:#006080;">', summary='</span> . $conn-&#62;quote($_POST[<span style="color:#006080;">'summary'</span>]) .
            <span style="color:#006080;">" WHERE id=$book[id]"</span>;
    }
    <span style="color:#0000ff;">else</span> { <span style="color:#008000;">//klo belum ada maka tambahkan data</span>
              $sql = <span style="color:#006080;">"INSERT INTO books(title, author, isbn, publisher,
              year,summary) VALUES("</span> .
            $conn-&#62;quote($_POST[<span style="color:#006080;">'title'</span>]) .
              <span style="color:#006080;">', '</span> . $conn-&#62;quote($_POST[<span style="color:#006080;">'author'</span>]) .
            <span style="color:#006080;">', '</span> . $conn-&#62;quote($_POST[<span style="color:#006080;">'isbn'</span>]) .
            <span style="color:#006080;">', '</span> . $conn-&#62;quote($_POST[<span style="color:#006080;">'publisher'</span>]) .
            <span style="color:#006080;">', '</span> . $conn-&#62;quote($_POST[<span style="color:#006080;">'year'</span>]) .
            <span style="color:#006080;">', '</span> . $conn-&#62;quote($_POST[<span style="color:#006080;">'summary'</span>]) .
            <span style="color:#006080;">')'</span>;
    }
    <span style="color:#0000ff;">try</span>
    {
        $conn-&#62;query($sql);
          header(<span style="color:#006080;">"Location: books.php"</span>);
          exit;
    }
    <span style="color:#0000ff;">catch</span>(PDOException $e)
    {
        $warnings[] = <span style="color:#006080;">'Error: Duplikasi ISBN..'</span>;
    }
  }
}
<span style="color:#0000ff;">else</span> {
     <span style="color:#008000;">// Form tidak tersubmit</span>
      $_POST = $book;
}

showHeader(<span style="color:#006080;">'Edit Book'</span>);

<span style="color:#0000ff;">if</span>(count($warnings)) {
      echo <span style="color:#006080;">"&#60;b&#62;Please correct these errors:&#60;/b&#62;&#60;br&#62;"</span>;
      <span style="color:#0000ff;">foreach</span>($warnings <span style="color:#0000ff;">as</span> $w)
      {
        echo <span style="color:#006080;">"- "</span>, htmlspecialchars($w), <span style="color:#006080;">"&#60;br&#62;"</span>;
      }
}

?&#62;

&#60;form action=<span style="color:#006080;">"editBook.php"</span> method=<span style="color:#006080;">"post"</span>&#62;
&#60;table border=<span style="color:#006080;">"1"</span> cellpadding=<span style="color:#006080;">"3"</span>&#62;
&#60;tr&#62;
    &#60;td&#62;Title&#60;/td&#62;
    &#60;td&#62;
      &#60;input type=<span style="color:#006080;">"text"</span> name=<span style="color:#006080;">"title"</span>
           <span style="color:#0000ff;">value</span>=<span style="color:#006080;">"&#60;?=htmlspecialchars($_POST['title'])?&#62;"</span>&#62;
    &#60;/td&#62;
  &#60;/tr&#62;
  &#60;tr&#62;
    &#60;td&#62;Author&#60;/td&#62;
    &#60;td&#62;
      &#60;select name=<span style="color:#006080;">"author"</span>&#62;
        &#60;option <span style="color:#0000ff;">value</span>=<span style="color:#006080;">""</span>&#62;Please select...&#60;/option&#62;
        &#60;?php <span style="color:#0000ff;">foreach</span>($authors <span style="color:#0000ff;">as</span> $id=&#62;$author) { ?&#62;
          &#60;option <span style="color:#0000ff;">value</span>=<span style="color:#006080;">"&#60;?=$id?&#62;"</span>
            &#60;?= $id == $_POST[<span style="color:#006080;">'author'</span>] ? <span style="color:#006080;">'selected'</span> : <span style="color:#006080;">''</span>?&#62;&#62;
            &#60;?=htmlspecialchars($author)?&#62;
          &#60;/option&#62;
        &#60;?php } ?&#62;
      &#60;/select&#62;
    &#60;/td&#62;
  &#60;/tr&#62;
  &#60;tr&#62;
    &#60;td&#62;ISBN&#60;/td&#62;
    &#60;td&#62;
      &#60;input type=<span style="color:#006080;">"text"</span> name=<span style="color:#006080;">"isbn"</span>
         <span style="color:#0000ff;">value</span>=<span style="color:#006080;">"&#60;?=htmlspecialchars($_POST['isbn'])?&#62;"</span>&#62;
    &#60;/td&#62;
  &#60;/tr&#62;
  &#60;tr&#62;
    &#60;td&#62;Publisher&#60;/td&#62;
    &#60;td&#62;
      &#60;input type=<span style="color:#006080;">"text"</span> name=<span style="color:#006080;">"publisher"</span>
         <span style="color:#0000ff;">value</span>=<span style="color:#006080;">"&#60;?=htmlspecialchars($_POST['publisher'])?&#62;"</span>&#62;
    &#60;/td&#62;
  &#60;/tr&#62;
  &#60;tr&#62;
    &#60;td&#62;Year&#60;/td&#62;
    &#60;td&#62;
      &#60;input type=<span style="color:#006080;">"text"</span> name=<span style="color:#006080;">"year"</span>
         <span style="color:#0000ff;">value</span>=<span style="color:#006080;">"&#60;?=htmlspecialchars($_POST['year'])?&#62;"</span>&#62;
    &#60;/td&#62;
  &#60;/tr&#62;
  &#60;tr&#62;
    &#60;td&#62;Summary&#60;/td&#62;
    &#60;td&#62;
      &#60;textarea name=<span style="color:#006080;">"summary"</span>&#62;&#60;?=htmlspecialchars(
                                    $_POST[<span style="color:#006080;">'summary'</span>])?&#62;&#60;/textarea&#62;
  &#60;/td&#62;
  &#60;/tr&#62;
  &#60;tr&#62;
    &#60;td colspan=<span style="color:#006080;">"2"</span> align=<span style="color:#006080;">"center"</span>&#62;
      &#60;input type=<span style="color:#006080;">"submit"</span> name=<span style="color:#006080;">"submit"</span> <span style="color:#0000ff;">value</span>=<span style="color:#006080;">"Save"</span>&#62;
    &#60;/td&#62;
  &#60;/tr&#62;
  &#60;/table&#62;
  &#60;?php <span style="color:#0000ff;">if</span>(@$book[<span style="color:#006080;">'id'</span>]) { ?&#62;
    &#60;input type=<span style="color:#006080;">"hidden"</span> name=<span style="color:#006080;">"book"</span> <span style="color:#0000ff;">value</span>=<span style="color:#006080;">"&#60;?=$book['id']?&#62;"</span>&#62;
  &#60;?php } ?&#62;
&#60;/form&#62;
&#60;?php
<span style="color:#008000;">// Display footer</span>
showFooter();
?&#62;
</pre>
</div>
<p>Kemudian tambahkan kode berikut pada halaman books.php </p>
<div>
<pre style="font-size:8pt;overflow:visible;width:100%;color:black;line-height:12pt;font-family:consolas, 'Courier New', courier, monospace;background-color:#f4f4f4;border-style:none;margin:0;padding:0;">&#60;tr&#62;
    &#60;td&#62;&#60;?=htmlspecialchars($r[<span style="color:#006080;">'title'</span>])?&#62;&#60;/td&#62;
    &#60;td&#62;&#60;?=htmlspecialchars($r[<span style="color:#006080;">'isbn'</span>])?&#62;&#60;/td&#62;
    &#60;td&#62;&#60;?=htmlspecialchars($r[<span style="color:#006080;">'publisher'</span>])?&#62;&#60;/td&#62;
    &#60;td&#62;&#60;?=htmlspecialchars($r[<span style="color:#006080;">'year'</span>])?&#62;&#60;/td&#62;
    &#60;td&#62;&#60;?=htmlspecialchars($r[<span style="color:#006080;">'summary'</span>])?&#62;&#60;/td&#62;
    &#60;td&#62;
      &#60;a href=<span style="color:#006080;">"editBook.php?book=&#60;?=$r['id']?&#62;"</span>&#62;Edit&#60;/a&#62; <span style="color:#008000;">//tambahan</span>
    &#60;/td&#62;
&#60;/tr&#62;

&#60;/table&#62;
&#60;a href=<span style="color:#006080;">"editBook.php"</span>&#62;Tambah Buku...&#60;/a&#62; <span style="color:#008000;">//tambahan</span>
</pre>
</div>
<p><a href="http://www2.ukdw.ac.id/kuliah/si/erickblog/PDOPHPDataObjects_1370F/image_8.png"><img style="border-width:0;" height="142" alt="image" src="http://www2.ukdw.ac.id/kuliah/si/erickblog/PDOPHPDataObjects_1370F/image_thumb_8.png" width="504" border="0"></a> </p>
<p>Ketika link edit ditekan maka muncul tampilan dibawah ini: </p>
<p><a href="http://www2.ukdw.ac.id/kuliah/si/erickblog/PDOPHPDataObjects_1370F/image_9.png"><img style="border-width:0;" height="323" alt="image" src="http://www2.ukdw.ac.id/kuliah/si/erickblog/PDOPHPDataObjects_1370F/image_thumb_9.png" width="254" border="0"></a> </p>
<p>Ketika link Tambah Buku ditekan maka tampil halaman berikut untuk menambah data:</p>
<p><a href="http://www2.ukdw.ac.id/kuliah/si/erickblog/PDOPHPDataObjects_1370F/image_10.png"><img style="border-width:0;" height="239" alt="image" src="http://www2.ukdw.ac.id/kuliah/si/erickblog/PDOPHPDataObjects_1370F/image_thumb_10.png" width="241" border="0"></a> </p>
<p>&#160;</p>
<h4>Membuat Fasilitas Edit Author</h4>
<p>Setalah membuat halaman untuk edit books maka sekarang kita akan membuat halaman untuk edit author, buat halaman dengan nama editauthor.php kemudian tambahkan kode berikut: </p>
<div>
<pre style="font-size:8pt;overflow:visible;width:100%;color:black;line-height:12pt;font-family:consolas, 'Courier New', courier, monospace;background-color:#f4f4f4;border-style:none;margin:0;padding:0;">&#60;?php
include(<span style="color:#006080;">'common.inc.php'</span>);

$id = (<span style="color:#0000ff;">int</span>)$_GET[<span style="color:#006080;">'author'</span>];

<span style="color:#0000ff;">if</span>($id){
    $q = $conn-&#62;query(<span style="color:#006080;">"select * from authors where id=$id"</span>);
    $author = $q-&#62;fetch(PDO::FETCH_ASSOC);
    $q-&#62;closeCursor();
    $q=<span style="color:#0000ff;">null</span>;
}
<span style="color:#0000ff;">else</span>{
    $author=array();
}

<span style="color:#0000ff;">if</span>($_POST[<span style="color:#006080;">'submit'</span>]){
    $warnings=array();

    <span style="color:#0000ff;">if</span>(!$_POST[<span style="color:#006080;">'firstName'</span>]) {
        $warnings[] = <span style="color:#006080;">'Silahkan masukan first name'</span>;
      }

      <span style="color:#0000ff;">if</span>(!$_POST[<span style="color:#006080;">'lastName'</span>]) {
        $warnings[] = <span style="color:#006080;">'Silahkan masukan last name'</span>;
      }

      <span style="color:#0000ff;">if</span>(!$_POST[<span style="color:#006080;">'bio'</span>]) {
        $warnings[] = <span style="color:#006080;">'Silahkan masukan bio'</span>;
      }

      <span style="color:#008000;">//jika tidak ditemukan error </span>
    <span style="color:#0000ff;">if</span>(count($warnings)==0){
            $sql = <span style="color:#006080;">"update authors set firstName="</span>.$conn-&#62;quote($_POST[<span style="color:#006080;">'firstName'</span>]).
            <span style="color:#006080;">",lastName="</span>.$conn-&#62;quote($_POST[<span style="color:#006080;">'lastName'</span>]).
            <span style="color:#006080;">",bio="</span>.$conn-&#62;quote($_POST[<span style="color:#006080;">'bio'</span>]).
            <span style="color:#006080;">" where id="</span>.$_POST[<span style="color:#006080;">'author'</span>];
        $conn-&#62;query($sql);
        header(<span style="color:#006080;">"Location: authors.php"</span>);
    }

}
<span style="color:#0000ff;">else</span> { <span style="color:#008000;">//form tidak disubmit</span>
    $_POST=$author;
}

showHeader(<span style="color:#006080;">"Edit Author"</span>);

<span style="color:#0000ff;">if</span>(count($warnings)){
    echo <span style="color:#006080;">"&#60;strong&#62;Error ditemukan :&#60;br/&#62;&#60;/strong&#62;"</span>;
    <span style="color:#0000ff;">foreach</span>($warnings <span style="color:#0000ff;">as</span> $w){
        echo <span style="color:#006080;">"- "</span>. htmlspecialchars($w), <span style="color:#006080;">"&#60;br/&#62;"</span>;;
    }
}
?&#62;

&#60;form action=<span style="color:#006080;">"editAuthor.php"</span> method=<span style="color:#006080;">"post"</span>&#62;
  &#60;table border=<span style="color:#006080;">"1"</span> cellpadding=<span style="color:#006080;">"3"</span>&#62;
  &#60;tr&#62;
    &#60;td&#62;First name&#60;/td&#62;
    &#60;td&#62;
      &#60;input type=<span style="color:#006080;">"text"</span> name=<span style="color:#006080;">"firstName"</span>
           <span style="color:#0000ff;">value</span>=<span style="color:#006080;">"&#60;?=htmlspecialchars($_POST['firstName'])?&#62;"</span>&#62;
    &#60;/td&#62;
  &#60;/tr&#62;
  &#60;tr&#62;
    &#60;td&#62;Last name&#60;/td&#62;
    &#60;td&#62;
      &#60;input type=<span style="color:#006080;">"text"</span> name=<span style="color:#006080;">"lastName"</span>
           <span style="color:#0000ff;">value</span>=<span style="color:#006080;">"&#60;?=htmlspecialchars($_POST['lastName'])?&#62;"</span>&#62;
               &#60;/td&#62;
  &#60;/tr&#62;
  &#60;tr&#62;
    &#60;td&#62;Bio&#60;/td&#62;
    &#60;td&#62;
      &#60;textarea name=<span style="color:#006080;">"bio"</span>&#62;&#60;?=htmlspecialchars($_POST[<span style="color:#006080;">'bio'</span>])?&#62;
      &#60;/textarea&#62;
    &#60;/td&#62;
  &#60;/tr&#62;
  &#60;tr&#62;
    &#60;td colspan=<span style="color:#006080;">"2"</span> align=<span style="color:#006080;">"center"</span>&#62;
         &#60;input type=<span style="color:#006080;">"submit"</span> name=<span style="color:#006080;">"submit"</span> <span style="color:#0000ff;">value</span>=<span style="color:#006080;">"Save"</span> /&#62;
    &#60;/td&#62;
  &#60;/tr&#62;
  &#60;/table&#62;

    &#60;input type=<span style="color:#006080;">"hidden"</span> name=<span style="color:#006080;">"author"</span> <span style="color:#0000ff;">value</span>=<span style="color:#006080;">"&#60;?=$_POST['id']?&#62;"</span> /&#62;

&#60;/form&#62;
&#60;?php
<span style="color:#008000;">// Display footer</span>
showFooter();
?&#62;
</pre>
</div>
<p>Kemudian pada halaman author.php tambahkan kode untuk link ke halaman editauthor sebagai berikut: </p>
<div>
<pre style="font-size:8pt;overflow:visible;width:100%;color:black;line-height:12pt;font-family:consolas, 'Courier New', courier, monospace;background-color:#f4f4f4;border-style:none;margin:0;padding:0;"><span style="color:#0000ff;">&#60;</span><span style="color:#800000;">tr</span><span style="color:#0000ff;">&#62;</span>
    <span style="color:#0000ff;">&#60;</span><span style="color:#800000;">td</span><span style="color:#0000ff;">&#62;&#60;?</span>=htmlspecialchars($r['firstName'])?<span style="color:#0000ff;">&#62;&#60;/</span><span style="color:#800000;">td</span><span style="color:#0000ff;">&#62;</span>
    <span style="color:#0000ff;">&#60;</span><span style="color:#800000;">td</span><span style="color:#0000ff;">&#62;&#60;?</span>=htmlspecialchars($r['lastName'])?<span style="color:#0000ff;">&#62;&#60;/</span><span style="color:#800000;">td</span><span style="color:#0000ff;">&#62;</span>
    <span style="color:#0000ff;">&#60;</span><span style="color:#800000;">td</span><span style="color:#0000ff;">&#62;&#60;?</span>=htmlspecialchars($r['bio'])?<span style="color:#0000ff;">&#62;&#60;/</span><span style="color:#800000;">td</span><span style="color:#0000ff;">&#62;</span>
    <span style="color:#0000ff;">&#60;</span><span style="color:#800000;">td</span><span style="color:#0000ff;">&#62;</span>
      <span style="color:#0000ff;">&#60;</span><span style="color:#800000;">a</span> <span style="color:#ff0000;">href</span>="<span style="color:#ff0000;">editAuthor</span>.<span style="color:#ff0000;">php</span>?<span style="color:#ff0000;">author</span>=&#38;<span style="color:#ff0000;">lt</span>;?=$<span style="color:#ff0000;">r</span>[<span style="color:#0000ff;">'id'</span>]?<span style="color:#0000ff;">&#62;</span>"<span style="color:#0000ff;">&#62;</span>Edit<span style="color:#0000ff;">&#60;/</span><span style="color:#800000;">a</span><span style="color:#0000ff;">&#62;</span>
    <span style="color:#0000ff;">&#60;/</span><span style="color:#800000;">td</span><span style="color:#0000ff;">&#62;</span>
<span style="color:#0000ff;">&#60;/</span><span style="color:#800000;">tr</span><span style="color:#0000ff;">&#62;</span>
</pre>
</div>
<p>&#160;</p>
<p>Sumber: Dennis Popel, "Learning PHP Data Object", Packt 2007.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[PHP wrapper class for Zend View]]></title>
<link>http://calisza.wordpress.com/?p=98</link>
<pubDate>Tue, 07 Oct 2008 13:43:49 +0000</pubDate>
<dc:creator>calisza</dc:creator>
<guid>http://calisza.cs.wordpress.com/2008/10/07/php-wrapper-class-for-zend-view/</guid>
<description><![CDATA[I recently posted an article with an example of a Zend Session wrapper I&#8217;ve been using for som]]></description>
<content:encoded><![CDATA[<p>I recently posted an article with an example of a Zend Session wrapper I've been using for some of my projects.</p>
<p>In that same vein I've created a simple wrapper for Zend View. I found this useful in instances where I didn't need to use Zend Framework's whole MVC implementation. Zend View is extremely helpful in creating a quick templating system for smaller projects or custom frameworks.</p>
<p>Once again I'll be assuming the following:</p>
<ul>
<li>You have installed <a href="http://framework.zend.com/docs/quickstart" target="_blank" title="Zend Framework quickstart">Zend Framework and set up the necessary include paths</a></li>
<li>You have read the <a href="http://framework.zend.com/manual/en/zend.view.html" target="_blank" title="Zend Framework View documentation">documentation pertaining to Zend_View</a></li>
</ul>
<p>First our view wrapper/abstraction class (view.php) :</p>
<p>[sourcecode language="php"]<br />
<?php<br />
/**<br />
 *<br />
 * LICENSE<br />
 *<br />
 * This source file is subject to the new BSD license that is bundled<br />
 * with this package in the file LICENSE.txt.<br />
 * If you did not receive a copy of the license and are unable to<br />
 * obtain it through the world-wide-web, please send an email<br />
 * to calisza@gmail.com so we can send you a copy immediately.<br />
 *<br />
 * @package    FlexiDev_View<br />
 * @copyright  Copyright (c) 2007 - 2008,  Flexible Developments - Barry Roodt (http://calisza.wordpress.com)<br />
 * @license    New BSD License<br />
 * @version    $Id: View.php Fri Oct 03 2008 1.0 barry roodt $<br />
 */<br />
 class View {<br />
 	public $tmplVars;<br />
 	public $view;</p>
<p> 	/**<br />
 		Constructor<br />
 	*/<br />
 	public function __construct(){</p>
<p> 		$this->tmplVars = array();<br />
 		// Instantiate our Zend View<br />
		$this->view = new Zend_View();</p>
<p>		/**<br />
		 * reset our basepath and scriptpaths, this is because we don't need the 'scripts', 'helpers' and 'filters' sub folders<br />
		 * relative to this script - of course you could change this as your needs require<br />
		 */<br />
		$this->view->setBasePath("./view");<br />
		$this->view->setScriptPath("./view");</p>
<p>		// set and assign some global vars to our template<br />
		// this is just an example - you can add more here<br />
		$globals  = array("base_url" => $_SERVER["HTTP_HOST"]);<br />
		$this->view->assign($globals);<br />
 	}<br />
 	/**<br />
	 * Method to add to our template variable stack<br />
	 * @param string variable name<br />
	 * @param mixed value<br />
	 */<br />
 	public function addTmplVar($key, $value){<br />
 		/* If our stack doesn't already exist, create a new array */<br />
 		if (!is_array($this->tmplVars)){<br />
 			$this->tmplVars = array($key=>$value);<br />
 		} else {<br />
 			// Add to our variable stack<br />
 			$this->tmplVars[$key] = $value;<br />
 		}<br />
 	}<br />
 	/**<br />
	 * Method to render the required view/template<br />
	 * @param string template script name<br />
	 * @param bool (optional) clear variable stack (default=true)<br />
	 */<br />
 	public function getTemplate($tmpl, $clearVars=true){<br />
 		/* Add our variable stack to the template */<br />
		$this->view->assign($this->tmplVars);<br />
		/* If required, clear our stack so that we can start with a fresh template on the next call */<br />
		if ($clearVars)<br />
			$this->tmplVars = "";</p>
<p>		/* Return the rendered template */<br />
		return $this->view->render($tmpl);<br />
	}</p>
<p> }</p>
<p>?><br />
[/sourcecode]</p>
<p>Next for some example usage (index.php) :</p>
<p>[sourcecode language="php"]<br />
<?php<br />
require_once("View.php");<br />
$items = array ("Name" => "Barry", "Surname" => "Roodt", "Title" => "Mr");<br />
$view = new View();<br />
$view->addTmplVar("myitems", $items);<br />
echo $view->getTemplate("template.phtml");<br />
?><br />
[/sourcecode]</p>
<p>And finally our view template (template.phtml) :</p>
<p>[sourcecode language="php"]</p>
<div>Hi <?php echo $this->myitems["name"]; ?></div>
<div>Here is some information for you<br />
<?php foreach($this->myitems as $key=>$val) : ?></p>
<p><strong><?php echo $key; ?>: </strong><?php echo $val; ?></p>
<p><?php endforeach; ?>
</div>
<div>You can also use Zend View's default helpers like so : <?php echo $this->escape($this->myitems["name"]); ?></div>
<p>[/sourcecode]</p>
<p>You can also view an example of this <a href="http://flexidev.co.za/dev/code/contact.zip" title="FlexiDev Contact Example">class in action here.</a></p>
<p>As always, comments, critiques and corrections welcome.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Moodle on a Mobile]]></title>
<link>http://ilite.wordpress.com/?p=90</link>
<pubDate>Tue, 07 Oct 2008 11:05:14 +0000</pubDate>
<dc:creator>ilite</dc:creator>
<guid>http://ilite.cs.wordpress.com/2008/10/07/moodle-on-a-mobile/</guid>
<description><![CDATA[Writing a blog sometimes suffers at the expense of the work that needs doing. I spent most of last w]]></description>
<content:encoded><![CDATA[<p>Writing a blog sometimes suffers at the expense of the work that needs doing. I spent most of last week tapping out some PHP code for a mobile version of Moodle.<br />
Now no, that does not mean Moodle is completely recoded for a Mobile device. It simply means that I can do a Moodle course on my Mobile. My test device of choice is the Nokia N95 8GB by the way.</p>
<p>Lets look at this post in two parts:<br />
<strong>Moodle:</strong><br />
I created a category in Moodle, called Mobile. I then built a short course in Moodle, putting all the content into the topic section on the front page of the lesson. Remember that a mobile device has a small screen (no shit sherlock, you think to yourself), and everything you add to the course has got to earn the right to be there. Remind yourself of this when you add an image, write text or plan the layout.</p>
<p>Cool, so now we have a course in Moodle, and you have enrolled for it. And you can change it's content, and you can do all the other Moodle stuff to it. Now lets look at the Mobile side.</p>
<p><strong>Mobile:</strong><br />
I access Moodle via the new bit of code that I wrote, and log in using my Moodle username and password. A page is then displayed allowing me to view my Mobile courses, Forum posts, and site news. Selecting the 'course' icon will display all the mobile courses that I have enrolled for. Select a course and off you go.</p>
<p>The easiest way to really understand this is to go and play with it.<br />
Username: mary<br />
Password: password<br />
Link: <a title="iLite Mobile Moodle" href="http://www.ilite.co.za/mlearn/" target="_blank">http://www.ilite.co.za/mlearn/</a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[MySQL Prepared Statements and PHP : A small experiment]]></title>
<link>http://rubayeet.wordpress.com/?p=78</link>
<pubDate>Tue, 07 Oct 2008 08:42:01 +0000</pubDate>
<dc:creator>rubayeet</dc:creator>
<guid>http://rubayeet.cs.wordpress.com/2008/10/07/mysql-prepared-statements-and-php-experiment/</guid>
<description><![CDATA[Consider a PHP-MySQL application where the information of 1000 users is being retrieved from the dat]]></description>
<content:encoded><![CDATA[<p style="text-align:justify;">Consider a PHP-MySQL application where the information of 1000 users is being retrieved from the database by running a for loop:<br />
<code><br />
for($i = 1; $i &#60;= 1000; $i++){</code></p>
<p><code>$query = "SELECT * FROM user WHERE user_id = $i";</code><br />
<code><br />
//run the query and fetch data</code><br />
<code>}</code></p>
<p style="text-align:justify;">In each iteration, the first thing the MySQL engine does is to parse the query for syntax check. Then it sets up the query and runs it. Since the query remains unchanged during each iteration(except for the value of user_id), parsing the the query each time is definitely an overhead. In such cases use of prepared statements is most convenient. A prepared statement is just like a typical query, except that it has 'placeholders' that are supplied values at run time. The prepared statement in this case will look like this:</p>
<p style="text-align:justify;"><code>"SELECT * FROM user WHERE user_id = ?"</code></p>
<p style="text-align:justify;">Notice the placeholder('?') for the value of user_id in the query. Now MySQL engine needs to parse the query only once, then execute it 1000 times by binding the placeholder with PHP script supplied value for user_id. This pre-parsing of the query results in a significant performance boost.</p>
<p style="text-align:justify;">The <a href="http://www.php.net/manual/en/book.mysqli.php" target="_blank">MySQL Improved extension</a> in PHP, more commonly known as <strong>MySQLi</strong>, provides a API to work with prepared statements. The documentation at the online PHP manual is good enough to get you started on how to use them on your PHP application, so I'll not go through it. Instead, I am going to share the results of my personal experiments on comparing performances of traditional and prepared SQL statements.</p>
<p style="text-align:justify;">I conducted the experiment after the launch of <a href="http://www,quizfarm.com" target="_blank">Quizfarm</a>. Quizfarm is a heavily trafficked site where users create and run quizzes. I wrote two separate scripts on our development server, both of which performed the same operation: selecting the quiz ID, quiz name and username of the quiz creator of all quizzes by joining the 'quiz' table (which had over 150,000 records) and the user table(over 350,000 records). One script used regular SQL statement, the other employed prepared statement techniques. Each script was executed three times and the time required to fetch the data was measured at each pass.</p>
<p><strong>The First script: traditional SQL statement</strong></p>
<p><code>//Get the Database link<br />
$dbLink    = getDBLink();</code><br />
<code><br />
$timeStart = microtime(true);</code><br />
<code><br />
for($i = 0; $i &#60; 162038; $i++){</code><br />
<code><br />
$query = "SELECT quiz_id, quiz_name, username as author FROM quiz q LEFT JOIN user u ON (q.owner_id = u.user_id) WHERE quiz_id = $i";</code><br />
<code><br />
if($result  = $dbLink-&#62;query($query)) </code><br />
<code>$obj = $result-&#62;fetch_object();</code><br />
<code><br />
else die("Failed to execute query: $dbLink-&#62;error");</code><br />
<code><br />
$result-&#62;close();</code><br />
<code><br />
}</code><br />
<code><br />
$timeEnd  = microTime(true);<br />
$dbLink-&#62;close();</code><br />
<code><br />
//measure the time difference<br />
$timeDiff = $timeEnd - $timeStart;</code></p>
<p><code>echo "Total time: $timeDiff seconds";</code></p>
<p><strong>Output:</strong></p>
<p>First Pass     -&#62; Total time: 25.5793459415 seconds<br />
Second Pass -&#62; Total time: 25.1708009243 seconds<br />
Third Pass    -&#62; Total time: 25.2259421349 seconds</p>
<p>Average: 25.32536300023 seconds</p>
<p><strong>The Second Script : using prepared statement</strong></p>
<p><code> $dbLink    = getDBLink();</code><br />
<code><br />
$query = "SELECT quiz_id, quiz_name, username as author FROM quiz q LEFT JOIN user u ON (q.owner_id = u.user_id) WHERE quiz_id = ?";</code><br />
<code><br />
$stmt  = $dbLink-&#62;stmt_init();</code><br />
<code><br />
if(!$stmt-&#62;prepare($query))<br />
die("Failed to prepare statement: ".$dbLink-&#62;error);</code></p>
<p><code>$timeStart = microtime(true);</code></p>
<p><code>for($i = 0; $i &#60; 162038; $i++) {</code><br />
<code><br />
$stmt-&#62;bind_param('i',$i);<br />
$stmt-&#62;execute();<br />
$stmt-&#62;bind_result($quizId, $quizName, $author);<br />
$stmt-&#62;fetch();<br />
$stmt-&#62;free_result();</code></p>
<p><code>}</code></p>
<p><code>$timeEnd  = microTime(true);</code><br />
<code><br />
$stmt-&#62;close();<br />
$dbLink-&#62;close();</code></p>
<p><code>$timeDiff = $timeEnd - $timeStart;</code></p>
<p><code>echo "Total time: $timeDiff seconds";</code></p>
<p><strong>Output:</strong></p>
<p>First  Pass    -&#62; Total time: 20.1434290409 seconds<br />
Second Pass -&#62; Total time: 20.182309866 seconds<br />
Third  Pass   -&#62; Total time: 20.6448199749 seconds</p>
<p>Average: 20.32351962726 seconds</p>
<p style="text-align:justify;"><strong>The task takes 20% less time for prepared statement, a significant performance boost.</strong></p>
<p style="text-align:justify;">Other than performance, it can also improve application security by guarding against SQL Injections. Check out this informative <a href="http://blogs.gotdotnet.com/sqlphp/archive/2008/09/30/how-and-why-to-use-parameterized-queries.aspx" target="_blank">blog post</a> on that topic.</p>
<p style="text-align:justify;">Harrison Fisk at MySQL AB wrote a <a href="http://dev.mysql.com/tech-resources/articles/4.1/prepared-statements.html">very good article</a> on MySQL prepared statements. Don't forget to check out the section <strong>'When should you use prepared statement?'</strong> if you read it.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Updates to Twiike (v.0.2) - Twitter your Nike+ runs!]]></title>
<link>http://jasonwiener.wordpress.com/?p=116</link>
<pubDate>Tue, 07 Oct 2008 06:35:38 +0000</pubDate>
<dc:creator>jasonwiener</dc:creator>
<guid>http://jasonwiener.cs.wordpress.com/2008/10/07/updates-to-twiike-v02-twitter-your-nike-runs/</guid>
<description><![CDATA[Just pushed an update to Twiike (figured why not make an update the same time Twitter was doing thei]]></description>
<content:encoded><![CDATA[<p>Just pushed an update to <a href="http://www.twiike.com">Twiike</a> (figured why not make an update the same time Twitter was doing theirs).</p>
<p>Enhancements in this release:</p>
<ul>
<li>Made signup 1-step using your Nike+ login.  This removes the need to use the "Share with friend" link from within Nike+.</li>
<li>Added pulldown menu to set default distance metric (km/mi) on your Twitter settings. This is now used for any runs published.  It's initially set based on your Nike+ user preferences.</li>
<li>Added the user tweets to the <a href="http://www.twitter.com/twiike">Twiike</a> timeline to drive additional traffic for <a href="http://www.twiike.com">Twiike</a> users</li>
<li>Added retrieve your password (which is set to your Nike+ password when you sign up).</li>
<li>Added ajax progress bars to all functions that require the server to respond so users don't think the site is not doing anything</li>
</ul>
<p>Please keep it coming with the suggestions.  I received a ton today and would love to know how to keep making it better for users.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Future Proof]]></title>
<link>http://adventtechnorati.wordpress.com/?p=8</link>
<pubDate>Tue, 07 Oct 2008 05:18:40 +0000</pubDate>
<dc:creator>perfectstar04</dc:creator>
<guid>http://adventtechnorati.cs.wordpress.com/2008/10/07/futureproof/</guid>
<description><![CDATA[In every codebase you run into unique challenges. Space and time complexity are the enterprise progr]]></description>
<content:encoded><![CDATA[<p>In every codebase you run into unique challenges. Space and time complexity are the enterprise programmer's nemeses, and all too often appear as cousins to another problem: extensibility.</p>
<p>The problem with making anything a solitary factor more expandable is that it increases the complexity required to interface with that feature by at least twice that factor &#8212; twice in the sense that time and complexity, remember them?, are lower-bounded to being capable of handling the expansion.</p>
<p>Case in point: The difference between a pre-populated list and one whose values are variant depending on which portions of a codebase are considered "active." This can pose quite the problem depending on how mission-critical this list is. (After all, this is a science; and all science should be repeatable <i>ad infinity</i>.) But how to retain this ability to accept a near-infinite range of values and manage them in some human-readable way?</p>
<p>Here we find the strengths and weaknesses of a language. In C, everything you touch is memory whether you realize it or not. From byte-pointers to malloc-ed blocks of hard disk, C keeps you up to your elbows in references. Perl scales the complexity back by a good factor, but grabbing references is still do-able: <code>$ref = \$scalar</code> is a direct accessor to the memory allocated by <code>$scalar</code>; and conversely, <code>$val = $$ref</code> gets the value of whatever variable resides at the memory location <code>$ref</code>. Pretty handy if you have an unknown-length set of variables with similar names. Now we have a common variable name we can manipulate without having a half-dozen Eval() functions in our code. (Aside: Eval() is nice, but sneakily evil; it's slow, offers arbitrary code execution if use improperly, and just plain ugly.) Our syntax highlighters can show us exactly what we meant, and in six months when we'll use this as the basis for the program's next feature, we'll have a much clearer idea of what the hell we wanted to get out of it.</p>
<p>But this is Perl. How do we do this in a language which masks references like PHP? Unfortunately, we can't go flying around the memory stack as easily as Perl does, but we can get pretty close with a single Eval(). (Aside 2: I know, I just got done bashing Eval(); I haven't forgotten, but we're in control of the string this code evaluates, so take a breath.)</p>
<p>PHP offers an arguably more elegant Eval() than most languages, the <a href="http://www.google.com/codesearch?q=lang%3Aphp%20%22%24{%24%22&#38;btnG=Search+Code">inline eval</a>. So let's reassume our situation: an unknown number of similarly-named variables is in our module's scope and we want an elegant, memorable way to access their values for modulation.<br />
In Perl:<br />
<code>$value_1 = "some important value";<br />
for($i=1; $i &#60; $some_known_upper_bound; $i++) {<br />
    $value_variable_name = "value_" . $i;<br />
    $value = $$value_variable_name;<br />
    # some modulator code<br />
}</code></p>
<p>In PHP:<br />
<code>$value_1 = "some important value";<br />
for($i = 1; $i &#60; $some_known_upper_bound; $i++) {<br />
    $value_variable_name = "value_" . $i;<br />
    # the magic...<br />
    $value = ${$value_variable_name};<br />
    # some modulator code<br />
}</code></p>
<p>And there you have it. Future proof code that modifies a like-named set of variables with a single, easily understood and aptly named variable.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[CakePHP, Prototype &amp; Json]]></title>
<link>http://toanhm.wordpress.com/?p=21</link>
<pubDate>Tue, 07 Oct 2008 02:44:31 +0000</pubDate>
<dc:creator>toanhm</dc:creator>
<guid>http://toanhm.cs.wordpress.com/2008/10/07/cakephp-prototype-json/</guid>
<description><![CDATA[Trong một bài viết gần đây, tôi có giới thiệu qua về một mô hình và công cụ]]></description>
<content:encoded><![CDATA[<p>Trong một <a href="http://toanhm.wordpress.com/2008/10/06/mo-hinh-he-thong-va-cong-cu/">bài viết gần đây,</a> tôi có giới thiệu qua về một mô hình và công cụ, frameworks để phát triển các sản phẩm cộng đồng cần khả năng chịu tải và mở rộng cao. CakePhp, Prototype &#38; Json là 3 công cụ đầu tiên mà chúng ta cần phải học. Tích hợp CakePhp, Prototype &#38; Json không khó, cái khó là bạn hiểu CakePhp như thế nào để tích hợp Json vào. Tôi mới chỉ biết đến cái không khó, còn cái khó kia thì từ từ tôi sẽ phải học tiếp vậy. Chúng ta bắt đầu tích hợp nào:</p>
<p>1. Download và cài đặt CakePhp 1.2x</p>
<p> </p>
<p>2. Download Prototype</p>
<p> </p>
<p>3. Cấu hình cho Json</p>
<p> </p>
<p>3. Một ví dụ đơn giản.</p>
<p> </p>
<p> </p>
<p>To be continous ...</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[There's no place like localhost: guide to setting up a web server]]></title>
<link>http://javadocs.wordpress.com/?p=64</link>
<pubDate>Tue, 07 Oct 2008 00:41:48 +0000</pubDate>
<dc:creator>joshjcarrier</dc:creator>
<guid>http://javadocs.cs.wordpress.com/2008/10/06/theres-no-place-like-localhost-guide-to-setting-up-a-web-server/</guid>
<description><![CDATA[So you want to set up a web server? Why would you want to do that, you say? It&#8217;s great for a n]]></description>
<content:encoded><![CDATA[<p>So you want to set up a web server? Why would you want to do that, you say? It's great for a number of reasons:</p>
<ul>
<li>hosting your own website, bulletin board, or blog</li>
<li>giving people read-only downloads (can be password protected!) to files</li>
<li>testing new versions of existing websites before they go live, <em>without requiring an Internet connection, which even includes <a href="http://developers.new.facebook.com/" target="_blank">developing Facebook applications</a></em></li>
<li>run your own instance of Wordpress</li>
<li>a great way to familiarize yourself with developing and deploying web applications</li>
</ul>
<div>I'll be guiding you to installing a server configured for the PHP Hypertext Processor (PHP). At the end, we can set up a MySQL database to store persistent data. Note that in this tutorial, there will be no direct linkage to this service - it's up to your application to do this.</div>
<div> </div>
<div>For most users, you should be following this basic server setup:</div>
<div> </div>
<div><strong>Step 1. Choosing a HTTP Server</strong></div>
<div style="padding-left:30px;">Many will argue that a robust, enterprise-level server like <a href="http://httpd.apache.org/" target="_blank">Apache </a>is required, but for most home usage purposes, which expect a relatively group of visitors on average hardware, I personally choose <a href="http://www.aprelium.com/abyssws/" target="_blank">Aprelium's Abyss X1 Server</a>. Versions are available for Windows, Mac and Linux. It is very user friendly - done completely through your web browser, compared to Apache, which requires text-editor modification of xml configuration files. </div>
<div style="padding-left:30px;">Install Abyss X1. You may also need to register for a free license key.</div>
<div style="padding-left:30px;">Follow the instructions available here to complete the setup.</div>
<div> </div>
<div><strong>Step 2. Installing PHP (optional)</strong></div>
<div style="padding-left:30px;">PHP is a language designed to integrate well into existing HTML code, allowing dynamic page content. If you don't need a PHP renderer, you may skip this step. Otherwise, if you're Windows, <a href="http://www.aprelium.com/abyssws/php5win.html" target="_blank">follow this instruction</a>, and for everyone else, <a href="http://www.aprelium.com/abyssws/php.html" target="_blank">follow this instruction</a>.</div>
<div> </div>
<div><strong>Step 3. Installing MySQL Database (optional)</strong></div>
<div style="padding-left:30px;">MySQL is a database, which is useful for keeping data around for longer than the browser session - comments, posts, and accounts can all be stored inside. There are other alternatives, such as Oracle XE and PostgreSQL, but my personal choice is MySQL for its simplicity to use.</div>
<div style="padding-left:30px;">All you'll need is to download and install the <a href="http://dev.mysql.com/downloads/" target="_blank">MySQL Community Server</a>. I also highly recommend the accompanying <a href="http://dev.mysql.com/downloads/gui-tools/" target="_blank">MySQL GUI Tools</a> to maintain users and databases.</div>
<div> </div>
<div>You can now connect, using <a href="http://localhost" target="_blank">http://localhost</a> (unless you changed the HTTP host's port during setup, default is 80) or your computer's local IP address. You will probably have to configure the HTTP documents folder to point to the right directory. And so that concludes this tutorial - writing the actual code to link PHP and MySQL, and setting up the MySQL databases will be for another day. We'll also look in a future post at how to access this web server from anywhere in the world.</div>
<div> </div>
<div>In the meantime, here's some other web server-driven software you may want to consider trying:</div>
<div>
<ul>
<li><a href="http://www.joomla.org/" target="_blank">Joomla </a>- Content Management System for fast configuration and deployment of many types of sites</li>
<li><a href="http://www.phpbb.com/" target="_blank">phpBB</a> - PHP bulletin board system</li>
<li><a href="http://www.phpmyadmin.net/home_page/downloads.php" target="_blank">phpMyAdmin</a> - manage MySQL databases from your browser</li>
<li><a href="http://wordpress.org/" target="_blank">Wordpress </a>- a blogging tool; currently powering this page!</li>
</ul>
<div>And here's some other servers you might want to run:</div>
<div>
<ul>
<li><a href="http://tomcat.apache.org/" target="_blank">Apache Tomcat</a> - supports Java Enterprise (J2EE) deployment</li>
<li><a href="http://filezilla-project.org/" target="_blank">FileZilla FTP Server</a> - file transfer over the regular file transfer protocol (Windows only)</li>
<li><a href="http://www.openssh.com/" target="_blank">OpenSSH </a>- secure protocol allowing remote terminal, X windows, SFTP</li>
<li><a href="http://openvpn.net/" target="_blank">OpenVPN</a> - keep your traffic secure when connecting from a public wireless location</li>
<li><a href="http://www.slimdevices.com/su_downloads.html" target="_blank">SqueezeCenter</a> - create your own personal Internet radio station while listening and viewing your library from anywhere</li>
</ul>
<div><em>Stay tuned!</em> - I'll be showing you how later to connect to your home, so that you or your visitors can visit your server without memorizing any numbers!</div>
</div>
</div>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Prologue]]></title>
<link>http://designtodevelop.wordpress.com/2008/10/06/prologue/</link>
<pubDate>Mon, 06 Oct 2008 23:45:42 +0000</pubDate>
<dc:creator>mattjharwood</dc:creator>
<guid>http://designtodevelop.cs.wordpress.com/2008/10/06/prologue/</guid>
<description><![CDATA[Bonjour, and welcome to Design / Development, a blog started to detail a designer&#8217;s attempt at]]></description>
<content:encoded><![CDATA[<p>Bonjour, and welcome to Design / Development, a blog started to detail a designer's attempt at learning more technical skills on the web. Target technologies include:</p>
<ul>
<li>Becoming reasonable at a scripting language, either PHP or Python</li>
<li>Working with XMPP / Jabber</li>
<li>Working with the <a href="http://openmicroblogging.org">OpenMicroBlogging</a> platform, and other Open protocols (OAuth, OpenID)</li>
<li>Create a fully-fledged web service</li>
</ul>
<p>I certainly hope you enjoy the ride!</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Repositorio funciones útiles/reutilizables PHP]]></title>
<link>http://blogricardo.wordpress.com/?p=150</link>
<pubDate>Mon, 06 Oct 2008 23:38:14 +0000</pubDate>
<dc:creator>makiolo</dc:creator>
<guid>http://blogricardo.cs.wordpress.com/2008/10/07/repositorio-funciones-utilesreutilizables-php/</guid>
<description><![CDATA[Llevo desde el 2005 trabajando para una pequeña empresa de informática como programador LAMP. En e]]></description>
<content:encoded><![CDATA[<p>Llevo desde el 2005 trabajando para una pequeña empresa de informática como programador LAMP. En estos años he acumulado muchas funciones potencialmente reutilizables e interesantes para cualquiera, aqui muestro una pequeña selección.</p>
<p>Os pido e invito a que añadáis vuestras propias funciones útiles o reutilizables en los comentarios.</p>
<p><!--more--></p>
<p>Define una tabla sql con parejas campo-valor como constantes de php. Una entrada de ejemplo válida podría ser : "select campo,valor from constantes"</p>
<pre>function definir_constante_sql($sql)
{
	$resultado=mysql_query($sql);
	if($resultado)
	{
		while($array=mysql_fetch_row($resultado))
		{
			define($array[0],$array[1]);
		}
	}
	else
	{
		echo "ERROR Grave , no se pudieron cargar las constantes";
		exit;
	}
}</pre>
<p>Nos devuelve un número de filas al azar de la tabla indicada.</p>
<pre>function dame_unas_filas_al_azar($tabla,$numero_de_filas)
{
$sql="SELECT * FROM ".$tabla." ORDER BY RAND(NOW()) LIMIT ".$numero_de_filas;
$resultado = mysql_query($sql);
	if($resultado)
	{
		return $resultado;
	}
	else
	{
		return false;
	}
}</pre>
<p>Devuelve el último ID de una tabla, usaba esto hasta que conocí mysql_last_id() -_-</p>
<pre>function ultimo_id($tabla,$campo)
{
$sql="SELECT max(".$campo.") AS maximo FROM `".$tabla."`";
$resultado=mysql_query($sql);
	if($resultado)
	{
		$array=mysql_fetch_array($resultado);
		$id_auto_asignado=$array['maximo'];
		return $id_auto_asignado;
	}
	else
	{
		return 0;
	}
}</pre>
<p>Nos dice si un valor existe.</p>
<pre>function si_existe_en_la_tabla($tabla,$campo,$valor)
{
	$tabla=mysql_escape_string($tabla);
	$campo=mysql_escape_string($campo);
	$valor=mysql_escape_string($valor);
	$sql="select ".$campo." from ".$tabla." where ".$campo."=".$valor;
	return (mysql_query($sql) &#38;&#38; (mysql_num_rows($resultado)&#62;0));
}</pre>
<p>Comprueba si vienes de la página pasada por parametro. OJO! No todos los navegadores definen HTTP_REFERER (ni tienen obligación de hacerlo), con todas las consecuencias que ello supone.</p>
<pre>function vienesDe($pagina)
{
	return strrchr($_SERVER['HTTP_REFERER'],"/") == "/".$pagina;
}</pre>
<p>Coge el valor del campo de una sql que devuelve al menos una fila.</p>
<pre>function coger_valor($sql,$campo)
{
	$resultado=mysql_query($sql);
	if($resultado)
	{
		$array=mysql_fetch_array($resultado);
		$valor=$array[$campo];
		return $valor;
	}
	else
	{
		return false;
	}
}</pre>
<p>Metido al principio, evita que el navegador use cache</p>
<pre>function no_coge_de_cache()
{
	header("Expires: Mon, 1 Jul 1900 00:00:00 GMT");
	header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
	header("Cache-Control: no-cache, must-revalidate");
	header("Pragma: no-cache");
}</pre>
<p>Genera un color aleatorio hexadecimal</p>
<pre>function generar_color()
{
	$r=rand(0,255);
	$g=rand(0,255);
	$b=rand(0,255);
	$color="#".dechex($r).dechex($g).dechex($b);
	return $color;
}</pre>
<p>Vacia una tabla !! para mysql 3.x o 4.x, en mysql 5.x esto es equivalente a TRUNCATE 'tabla'</p>
<pre>function vaciar_tabla($tabla)
{
	$sql="DELETE FROM `".$tabla."`";mysql_query($sql);
	$sql="ALTER TABLE `".$tabla."` PACK_KEYS =0 CHECKSUM =0 DELAY_KEY_WRITE =0 AUTO_INCREMENT =1";mysql_query($sql);
}</pre>
<p>Redirecciona por javascript, en lugar de por header(Location : pagina.php).</p>
<pre>function redireccionarPorJavascript($nuevaURL)
{
	echo '&#60;script type="text/javascript"&#62;';
	echo 'location.href="'.$nuevaURL.'"';
	echo '&#60;/script&#62;';
}</pre>
<p>Capitaliza una palabra</p>
<pre>function capitalizar($palabra)
{
	return ucfirst(strtolower($palabra));
}</pre>
<p>Si tenemos tablas definidas con enumerado podemos obtener un array de ese enumerado con esta función, la sintaxis es tabla.columna</p>
<pre>/*
$array = enum("tabla.columna");
*/
function enum($objeto)
{
	list($tabla, $columna) = explode(".", $objeto);
	$fila=@mysql_fetch_assoc(mysql_query("SHOW COLUMNS FROM ".$tabla." LIKE
	'".$columna."'"));
	return ($fila ? explode("','",preg_replace("/(enum&#124;set)\('(.+?)'\)/","\\2",$fila['Type'])) : array(0=&#62;'None'));
}</pre>
<p>Nos dice si una definición esta definida.</p>
<pre>function estaDefinido($var)
{
	return (isset($var) &#124;&#124; $var != "" &#124;&#124; $var != null &#124;&#124; strlen($var)&#62;0);
}</pre>
<p>Borra un registro</p>
<pre>function borrarRegistro($tabla , $nombreCampoClave , $valorCampoClave)
{
	$sql="DELETE FROM `".$tabla."` WHERE `".$nombreCampoClave."` = '".$valorCampoClave."' LIMIT 1;";
	return mysql_query($sql);
}</pre>
<p>Actualiza un campo</p>
<pre>function actualizar_campo($tabla , $nombreCampoUnico , $valorCampoUnico , $nombreColumna , $nuevoValorColumna)
{
	$sql="UPDATE `".$tabla."` SET `".$nombreColumna."` = '".$nuevoValorColumna."' WHERE `".$nombreCampoUnico."` = '".$valorCampoUnico."' LIMIT 1 ;";
	return mysql_query($sql);
}</pre>
<p>Ver las "superglobales" definidas.</p>
<pre>function versupervariables()
{
	echo "<strong>_COOKIE</strong>";
	foreach($_COOKIE as $clave=&#62;$valor)
	{
		echo $clave." = ".$valor."";
	}
	echo "<strong>_ENV</strong>";
	foreach($_ENV as $clave=&#62;$valor)
	{
		echo $clave." = ".$valor."";
	}
	echo "<strong>_FILES</strong>";
	foreach($_FILES as $clave=&#62;$valor)
	{
		echo $clave." = ".print_r($valor)."";
	}
	echo "<strong>_GET</strong>";
	foreach($_GET as $clave=&#62;$valor)
	{
		echo $clave." = ".$valor."";
	}
	echo "<strong>_POST</strong>";
	foreach($_POST as $clave=&#62;$valor)
	{
		echo $clave." = ".$valor."";
	}
	echo "<strong>_REQUEST</strong>";
	foreach($_REQUEST as $clave=&#62;$valor)
	{
		echo $clave." = ".$valor."";
	}
	echo "<strong>_SESSION</strong>";
	foreach($_SESSION as $clave=&#62;$valor)
	{
		echo $clave." = ".$valor."";
	}
	echo "<strong>_SERVER</strong>";
	foreach($_SERVER as $clave=&#62;$valor)
	{
		echo $clave." = ".$valor."";
	}
}</pre>
<p>Acota una palabra con puntos suspensivos.</p>
<pre>function acotar($palabra , $cantidadDeseada , $porDelante = false)
{
	$sufijo = "...";
	if(strlen($palabra)&#62;$cantidadDeseada)
	{
		if($porDelante)
		{
			return $sufijo.substr($palabra,strlen($palabra)-$cantidadDeseada,strlen($palabra)-1);
		}
		else
		{
			return substr($palabra,0,$cantidadDeseada-strlen($sufijo)).$sufijo;
		}
	}
	else
	{
		return $palabra;
	}
}</pre>
<p>Si el valor de un GET es numero ---&#62; bool</p>
<pre>function porElGETvieneUnNumero($nombre)
{
	return (isset($_GET[$nombre]) &#38;&#38; $_GET[$nombre]!="" &#38;&#38; is_numeric($_GET[$nombre]));
}</pre>
<p>Esta función recibe un timestamp he imprime hace cuando fue esa fecha adaptandose al mejor periodo de tiempo posible. Por ejemplo "Por ejemplo: Hace 3 dias"</p>
<pre>function hace($timestamp)
{
	$diferencia = time() - $timestamp;
	if($diferencia &#62; 0)
	{
		$periodo = array("seg", "min", "hora", "dia", "semana", "mes" , "año", "decada");
		$longitud = array(    "60" ,"60"  , "24" ,  "7"  , "4.35",   "12" , "10" );

		for($j = 0; $diferencia &#62;= $longitud[$j]; $j++)
			$diferencia /= $longitud[$j];

		$diferencia = round($diferencia);

		if($diferencia != 1)
		{
			if($periodo[$j] == "mes")
				$periodo[$j].= "es";
			else
				$periodo[$j].= "s";
		}

		return "Hace <strong>".$diferencia."</strong> ".$periodo[$j];
	}
	else
	{
		return "Ahora mismo";
	}
}</pre>
<p>Nos dice si un año es bisiesto</p>
<pre>function esBisiesto($ano)
{
	// El dia y el mes me lo invento por que no interesa
	return (date("L",strtotime($ano."-2-28")) == 1);
}</pre>
<p>Nos dice el limite de un mes, teniendo en cuanta bisiestos con la función anterior</p>
<pre>function getLimiteMes($mes,$ano)
{
	switch($mes)
	{
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
		case 12:
			return 31;
		break;

		case 2:
			if(esBisiesto($ano))
			{return 29;}
			else
			{return 28;}
		break;

		case 4:
		case 6:
		case 9:
		case 11:
		default:
			return 30;
		break;
	}
}</pre>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Solar Framework: MySQL Replication Adapter]]></title>
<link>http://phpimpact.wordpress.com/?p=889</link>
<pubDate>Mon, 06 Oct 2008 22:07:51 +0000</pubDate>
<dc:creator>Federico</dc:creator>
<guid>http://phpimpact.cs.wordpress.com/2008/10/06/solar-framework-mysql-replication-adapter/</guid>
<description><![CDATA[As part of the Solar-1.0.0alpha2 release, Paul M. Jones included an SQL adapter that lets you connec]]></description>
<content:encoded><![CDATA[<p>As part of the Solar-1.0.0alpha2 release, Paul M. Jones included an SQL adapter that lets you connect to master/slave MySQL installations.</p>
<h3>Replication</h3>
<p>Replication enables data from one MySQL database server (called the     master) to be replicated to one or more MySQL database servers     (slaves). Replication is asynchronous - your replication slaves do     not need to be connected permanently to receive updates from the     master, which means that updates can occur over long-distance     connections and even temporary solutions such as a dial-up service.     Depending on the configuration, you can replicate all databases,     selected databases, or even selected tables within a data.</p>
<h3>Solar Adapter</h3>
<p>When you get into a situation where you need to scale up, you might need a replicated MySQL database setup. In such cases, there is one "master" server that handles reads and writes, and there are one or more "slave" servers that are read-only. This means you need to pick which server you're going to connect to based on the kind of statement you need to issue (SELECT, INSERT, UPDATE, etc).</p>
<p>The Solar_Sql_Adapter_MysqlReplicated adapter handles all the connections and switching-around for you, and you don't need change a single line of application code. All you need to do is modify your configuration file to tell it where your master and slave servers are.</p>
<p>More: <a href="http://solarphp.com/blog/read/19-adapter-for-master-slave-my-sql-setups" target="_blank">Adapter for Master/Slave MySQL Setups</a></p>
<h3>Related Links</h3>
<ul>
<li><a href="http://aciddrop.com/2008/01/10/step-by-step-how-to-setup-mysql-database-replication/" target="_blank">Step-by-step: How to setup MySQL Database replication</a></li>
<li><a href="http://dev.mysql.com/doc/refman/5.0/en/replication.html" target="_blank">MySQL Replication</a></li>
<li><a href="http://devzone.zend.com/article/3884-Scaling-Day-By-Day" target="_blank">Jayson Minard: Scaling Day-By-Day</a></li>
</ul>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Nifty time-saving form / validation function for CodeIgniter]]></title>
<link>http://momgeek.wordpress.com/?p=58</link>
<pubDate>Mon, 06 Oct 2008 17:49:45 +0000</pubDate>
<dc:creator>fast times at sweet valley high</dc:creator>
<guid>http://momgeek.cs.wordpress.com/2008/10/06/nifty-time-saving-form-validation-function-for-codeigniter/</guid>
<description><![CDATA[Note: This needs to be seriously tweaked to work better with more complex model functions.  I am le]]></description>
<content:encoded><![CDATA[<p><span style="color:#ff0000;"><strong>Note: This needs to be seriously tweaked to work better with more complex model functions.  I am leaving this up but understand that for now it only handles one-variable model functions easily.</strong></span></p>
<p>I'm lazy when I code. By lazy I mean I detest retyping the same several codes of line multiple times throughout an app. My motto is (usually) if I have to use a/several line(s) more than 3 times it becomes a function so I can use and re-use it.</p>
<p>If you're like me, when you use the form features in CI you set up the controller part like so:</p>
<p><code><br />
if($this-&#62;validation-&#62;run() == FALSE) {<br />
$data["variable"] = "something";<br />
$this-&#62;load-&#62;view("view_template",$data);<br />
} else {<br />
$process = $this-&#62;model_name-&#62;model_function($this-&#62;validation-&#62;variable);<br />
//Success / error message here<br />
}</code></p>
<p>That (extremely simple) example uses only 7 lines of code. However, if you have an add + edit function in each controller and you have 10 controllers, that's (7+7)*10 = 140 lines that are really similar. I hear a function calling my name!</p>
<p>With the function I created I took those six lines of code and reduced them to this:<br />
<code>$this-&#62;library_name-&#62;validation_run("model_name","model_function",$this-&#62;validation-&#62;variable,"view_template",array("variable"=&#62;"something");</code></p>
<p>Pretty sweet, no? :)</p>
<p>Below is the function. I am assuming you have a basic to intermediate understanding of CI, so I won't go into a lot of depth explaining it. I placed validation_run in the custom forms library I use. You can use it in your own custom library or create a library out of it. If you put it in your own library, ensure that the method you are using to reference CI functions is reflected in validation_run ($this-&#62;obj,$ci,$this-&#62;ci, etc). Also ensure that the Validation and Model are loaded prior to calling validation_run.</p>
<p><code>function validation($model_name,$model_function,$model_function_variable,$layout_template,$data_array=NULL)<br />
{</code><code><br />
if($this-&#62;ci-&#62;validation-&#62;run() == FALSE) {<br />
//This allows the view to be called with or without parameters.<br />
if(!is_null($data_array)) {<br />
$this-&#62;ci-&#62;load-&#62;view($layout_template,$data_array);<br />
} else {<br />
$this-&#62;ci-&#62;load-&#62;view($layout_template);<br />
}<br />
} else {<br />
$process = $this-&#62;ci-&#62;$model_name-&#62;$model_function(</code><code>$model_function_variable</code><code>);<br />
//Use your favorite redirection method here<br />
}<br />
}</code></p>
<p>To use it, you'd simply call</p>
<p><code>$this-&#62;library_name-&#62;validation_run("model_name","model_function",$this-&#62;validation-&#62;variable,"view_template",array("variable"=&#62;"something");</code></p>
<p>For better readability you could do alternatively do it this way:</p>
<p><code>$this-&#62;library_name-&#62;validation_run(<br />
"model_name",<br />
"model_function",<br />
$this-&#62;validation-&#62;variable,<br />
"view_template",<br />
array("variable"=&#62;"something"<br />
);</code></p>
<p>Of course, you'd replace library_name with the library name you called it from.</p>
<p>Not everyone will have a use for this function; it's really only good for simple validation "running" . However, it's saved me so much time coding that I had to share it :)</p>
<p>Enjoy!</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Find the duration in hours and minutes of two times using PHP]]></title>
<link>http://40shadows.wordpress.com/?p=243</link>
<pubDate>Mon, 06 Oct 2008 13:10:37 +0000</pubDate>
<dc:creator>Yusuf Abdulla Shunan</dc:creator>
<guid>http://40shadows.cs.wordpress.com/2008/10/06/find-the-duration-of-two-times-using-php/</guid>
<description><![CDATA[Another function that you can use to find the duration of any given two times. If you know PHP you c]]></description>
<content:encoded><![CDATA[<p>Another function that you can use to find the duration of any given two times. If you know PHP you can modify this further to include years, days &#38; months (if you need help let me know!). But right now it will only say the time differences of two inputted times, which is actually what I need for now!</p>
<p>function duration($start,$end){<br />
$tmp_e = explode(":",$end);<br />
$tmp_s = explode(":",$start);<br />
$start_time = mktime($tmp_s[0],$tmp_s[1],$tmp_s[2],8,8,8);<br />
$end_time = mktime($tmp_e[0],$tmp_e[1],$tmp_e[2],8,8,8);<br />
$durationt = $end_time-$start_time;<br />
$hrs = intval(floor($durationt/3600));<br />
$min = intval(floor($durationt/60))-($hrs*60);<br />
if($hrs&#60;&#62;0){<br />
$rval = $hrs.' hr';<br />
}<br />
if($min&#60;&#62;0){<br />
if($hrs&#60;&#62;0){<br />
$rval .= ' &#38; '.$min.' min';<br />
} else {<br />
$rval = $min.' min';<br />
}<br />
}<br />
return $rval;<br />
}</p>
<p>How to use it:</p>
<p>$timeOne ='12:31';</p>
<p>$timeTwo = '15:43';</p>
<p>echo duration($timeOne,$timeTwo); //output: 3 hours &#38; 12 min</p>
]]></content:encoded>
</item>

</channel>
</rss>
