PHP Classes

File: fwphp/glomodul/blog/msgmkd/altervista005.txt

Recommend this page to a friend!
  Classes of Slavko Srakocic   B12 PHP FW   fwphp/glomodul/blog/msgmkd/altervista005.txt   Download  
File: fwphp/glomodul/blog/msgmkd/altervista005.txt
Role: Documentation
Content type: text/plain
Description: Documentation
Class: B12 PHP FW
Manage database records with a PDO CRUD interface
Author: By
Last change: Update of fwphp/glomodul/blog/msgmkd/altervista005.txt
Date: 1 year ago
Size: 10,774 bytes
 

Contents

Class file image Download
5\. CRUD simple table (ID, ...some data) PDO SQLite =================================================== **[HOME ](http://phporacle.altervista.org/php-oracle-main-menu/)2.Sept.2015 Download - see site\_ver2.rar from my article 9.** Excellent code to learn object oriented programming, model-view-controller code separation (structured programming), single page application (require scripts, not URL them), most code outside Apache doc root. **1\. Download sqlitestudio and install DDL below.** \--\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* -- sqlite 3 --\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* /\* SELECT \* FROM message ; select \* from zodiac ; \*/ /\* http://dev:8083/test/books/a01cookbook/tema.php J:\\dev\_web\\htdocs\\test\\books\\a01cookbook\\tema.php sqlite db is: J:\\dev\_web\\htdocs\\test\\books\\a01cookbook\\tema.sqlite SELFJOIN TABLE : 1. C INSERT frm data, 2. R DISPLAY tbl, row, 3. V VALIDATE, E set\_exception\_handler Not neccessarily here: U UPDATE and D DELETE WITH J:\\aplp\\aplp\\sqlitestudio\\SQLiteStudio.exe TEME (msgs-PORUKE I replays-ODGOVORI) SELFJOIN TEME (msgs-PORUKE I replays-ODGOVORI) SELFJOIN ---------------------------------------------------------------- 5 KEYS: id,thread\_id,parent\_id,level,thread\_pos ---------------------------------------------------------------- 1 1 0 0 0 TEMA1 (thread1) by ss @ 2015-03-25 00:41 (99 bytes) 2 1 1 1 1 funkcije by ss @ 2015-03-25 00:42 (242 bytes) 3 1 2 2 2 funkcija save() by ss @ 2015-03-25 00:52 (1335 bytes) 6 1 2 2 3 funkcija frm\_post() by ss @ 2015-03-25 19:29 (303 bytes) 4 2 0 0 0 TEMA2 CRUD ?ifrarnika sqlite3 by ss ... 5 3 0 0 0 TEMA3 MAPE web servera by ss ... \_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_ Otvoriti novu temu (nit, thread) \*/ -- sqlite db: J:\\dev\_web\\htdocs\\test\\books\\a01cookbook\\tema.sqlite CREATE TABLE message ( id INTEGER PRIMARY KEY AUTOINCREMENT, posted\_on DATETIME NOT NULL, author CHAR(255), subject CHAR(255), body MEDIUMTEXT, thread\_id INT UNSIGNED NOT NULL, parent\_id INT UNSIGNED NOT NULL, level INT UNSIGNED NOT NULL, thread\_pos INT UNSIGNED NOT NULL ); --sqlite db: J:\\dev\_web\\htdocs\\test\\books\\a01cookbook\\zodiac.sqlite CREATE TABLE zodiac ( id INT UNSIGNED NOT NULL, sign CHAR(11), symbol CHAR(13), planet CHAR(7), element CHAR(5), start\_month TINYINT, start\_day TINYINT, end\_month TINYINT, end\_day TINYINT, PRIMARY KEY(id) ) ; INSERT INTO zodiac VALUES (1,'Aries','Ram','Mars','fire',3,21,4,19); INSERT INTO zodiac VALUES (2,'Taurus','Bull','Venus','earth',4,20,5,20); INSERT INTO zodiac VALUES (3,'Gemini','Twins','Mercury','air',5,21,6,21); INSERT INTO zodiac VALUES (4,'Cancer','Crab','Moon','water',6,22,7,22); INSERT INTO zodiac VALUES (5,'Leo','Lion','Sun','fire',7,23,8,22); INSERT INTO zodiac VALUES (6,'Virgo','Virgin','Mercury','earth',8,23,9,22); INSERT INTO zodiac VALUES (7,'Libra','Scales','Venus','air',9,23,10,23); INSERT INTO zodiac VALUES (8,'Scorpio','Scorpion','Mars','water',10,24,11,21); INSERT INTO zodiac VALUES (9,'Sagittarius','Archer','Jupiter','fire',11,22,12,21); INSERT INTO zodiac VALUES (10,'Capricorn','Goat','Saturn','earth',12,22,1,19); INSERT INTO zodiac VALUES (11,'Aquarius','Water Carrier','Uranus','air',1,20,2,18); INSERT INTO zodiac VALUES (12,'Pisces','Fishes','Neptune','water',2,19,3,20); **2\. Controller and view ~ 120 lines : ** <php // http://dev:8083/test/books/a01cookbook/ // J:\\dev\_web\\htdocs\\test\\books\\a01cookbook\\zodiac.php // \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* // 1. M O D E L - file where b u i l d\_ q u e r y ( ) is defined // \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* $fields = array( 'sign' , 'symbol' , 'planet' , 'element' , 'start\_month' , 'start\_day' , 'end\_month' , 'end\_day' ); $lbls = array( 'Znak' , 'Simbol' , 'Planeta' , 'Element' , 'Od mjeseca' , 'Od dana' , 'Do mjeseca' , 'Do dana' ); **include \_\_DIR\_\_ . '/mdl.php';** $db = new PDO('sqlite:zodiac.sqlite'); $db->setAttribute(PDO::ATTR\_ERRMODE, PDO::ERRMODE\_EXCEPTION); // \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* // 2. C O N T R O L L E R // \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* $cmd = isset($\_REQUEST\['cmd'\]) $\_REQUEST\['cmd'\] : 'show'; switch ($cmd) { case 'edit': try { $st = $db->prepare('SELECT ' . implode(',',$fields) . ' FROM zodiac WHERE id = '); $st->execute(array($\_GET\['id'\])); $row = $st->fetch(PDO::FETCH\_ASSOC); } catch (Exception $e) { $row = array(); } case 'add': print '<form method="post" action="' . htmlentities($\_SERVER\['PHP\_SELF'\]) . '">'; print '<input type="hidden" name="cmd" value="save">'; print '<table>'; if ('edit' == $cmd) { printf('<input type="hidden" name="id" value="%d">', $\_GET\['id'\]); } foreach ($fields as $field) { if ('edit' == $cmd) { $value = htmlentities($row\[$field\]); } else { $value = ''; } printf('<tr><td>%s: </td><td><input type="text" name="%s" value="%s">', $field, $field, $value); printf('</td></tr>'); } print '<tr> <td></td> <td><input type="submit" value="Save"></td> </tr>'; print '</table></form>'; break; case 'save': try { $st = build\_query($db,'id',$fields,'zodiac'); print 'Added info.'; } catch (Exception $e) { print "Couldn't add info: " . htmlentities($e->getMessage()); } print '<hr>'; case 'show': // \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* // 3. V I E W - P A G I N A T O R // \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* default: $self = htmlentities($\_SERVER\['PHP\_SELF'\]); /\* without P A G I N A T O R : foreach ($db->query('SELECT id,sign FROM zodiac') as $row) { printf('<li> <a href="%scmd=edit&id=%s">%s</a>', $self,$row\['id'\],htmlentities($row\['sign'\])); } \*/ $offset = isset($\_GET\['offset'\]) intval($\_GET\['offset'\]) : 1; if (! $offset) { $offset = 1; } $per\_page = 10; $total = $db->query('SELECT COUNT(\*) FROM zodiac')->fetchColumn(0); $limitedSQL = 'SELECT \* FROM zodiac ORDER BY id ' . "LIMIT $per\_page OFFSET " . ($offset-1); $lastRowNumber = $offset - 1; print '<a href="'.$self.'cmd=add">Dodati redak</a><hr />'; print '<ol>'; foreach ($db->query($limitedSQL) as $row) { $lastRowNumber++; //print "{$row\['sign'\]}" printf('<li> <a href="%scmd=edit&id=%s">%s</a>', $self,$row\['id'\],htmlentities($row\['sign'\])); echo ", {$row\['symbol'\]} ({$row\['id'\]}) <br/>\\n"; } print '</ol>'; // indexed\_links($total,$offset,$per\_page); print "<br/>"; print "(Prikazani retci $offset - $lastRowNumber od $total)"; // break; } // e n d s w i t c h **3\. Model- universal code ~ 70 lines :** <php function build\_query($db, $key\_field, $fields, $table) { $values = array(); if (! empty($\_POST\[$key\_field\])) { $update\_fields = array(); foreach ($fields as $field) { $update\_fields\[\] = "$field = "; // Assume data is coming from a form $values\[\] = $\_POST\[$field\]; } // Add the key field's value to the $values array $values\[\] = $\_POST\[$key\_field\]; $st = $db->prepare("UPDATE $table SET " . implode(',', $update\_fields) . "WHERE $key\_field = "); } else { // Start values off with a unique ID // If your DB is set to generate this value, use NULL instead $values\[\] = md5(uniqid()); $placeholders = array(''); foreach ($fields as $field) { // One placeholder per field $placeholders\[\] = ''; // Assume the data is coming from a form $values\[\] = $\_POST\[$field\]; } $st = $db->prepare( "INSERT INTO $table ($key\_field," . implode(',',$fields) . ') VALUES ('. implode(',',$placeholders) .')'); } $st->execute($values); return $st; } function print\_link($inactive,$text,$offset='') { if ($inactive) { print "<span class='inactive'>$text</span>"; } else { print "<span class='active'>". "<a href='" . htmlentities($\_SERVER\['PHP\_SELF'\]) . "offset=$offset'>$text</a></span>"; } } function indexed\_links($total,$offset,$per\_page) { $separator = ' | '; // print\_link($offset == 1, '<< Preth', max(1, $offset - $per\_page)); // print all groupings except last one for ($start = 1, $end = $per\_page; $end < $total; $start += $per\_page, $end += $per\_page) { print $separator; print\_link($offset == $start, "$start-$end", $start); } /\* print the last grouping - \* at this point, $start points to the element at the beginning \* of the last grouping \*/ /\* the text should only contain a range if there's more than \* one element on the last page. For example, the last grouping \* of 11 elements with 5 per page should just say "11", not "11-11" \*/ $end = ($total > $start) "-$total" : ''; print $separator; print\_link($offset == $start, "$start$end", $start); // print $separator; print\_link($offset == $start, 'Sljed >>',$offset + $per\_page); } kod[ edit]($web_docroot_url/inc/utl/edservertxt.php)[ phpinfo]($web_docroot_url/phpinfo_inc.php) EOKOD; /\* call it so: kod\_edit\_run( $idx // script\_dir\_path , $idxscript // script\_name , MDURL); // web\_docroot\_url = (Apache) web server URL \*/ }