Site Sponsors:
An Easy PHP CRUD Example ... for SQL / Sqlite! 
When our needs are simple, then so should be our code.

For 100% of what we need to do at the moment (manage a massive collection of data across a local network,) this class will do what we need it to do: CRUD far too many rows consisting of TEXT / string values!


So, is DAO-generation necessary? When using a name-associated array in PHP 5, all we need do is to define our fields, and away we go!


class SqlStringRecord {

function get_file_name() {
return "default.sqlt3";
}

function get_table_name() {
return "contacts";
}

function get_columns() {
$data = array();
$data[0] = "Name";
$data[1] = "Address";
$data[2] = "Note";
return $data;
}

function delete_table() {
$db = new SQLite3($this->get_file_name());
$tbl = $this->get_table_name();
$db->exec("DROP TABLE IF EXISTS $tbl");
$db->close();
if ($db->lastErrorCode() != 0) {
return FALSE;
}
return TRUE;
}

function create_table() {
$this->delete_table();
$fields = $this->get_columns();
$tbl = $this->get_table_name();
$cmd = "CREATE TABLE $tbl (ID INTEGER PRIMARY KEY AUTOINCREMENT";
foreach ($fields as $field) {
$cmd .= ', ';
$cmd .= $field;
$cmd .= ' STRING';
}
$cmd .= ")";
$db = new SQLite3($this->get_file_name());
$db->exec($cmd);
$db->close();
if ($db->lastErrorCode() != 0) {
return FALSE;
}
return TRUE;
}

function count() {
$db = new SQLite3($this->get_file_name());
$tbl = $this->get_table_name();
$rs = $db->query("SELECT COUNT(*) FROM $tbl");
if ($rs == FALSE) {
return FALSE;
}
$data = $rs->fetchArray();
$db->close();
return $data[0];
}

function create($special) {
$cols = $this->get_columns();
$tbl = $this->get_table_name();
$cmd = "INSERT INTO $tbl (";
$bfirst = true;
foreach ($cols as $col) {
if ($bfirst == false) {
$cmd .= ", ";
}
$cmd .= $col;
$bfirst = false;
}
$cmd .= ") VALUES (";
$bfirst = true;
foreach ($cols as $col) {
if ($bfirst == false) {
$cmd .= ", ";
}
$cmd .= "'$special[$col]'";
$bfirst = false;
} $cmd .= ")";
echo "\n\n$cmd\n\n";
$db = new SQLite3($this->get_file_name());
$db->exec($cmd);
$db->close();
if ($db->lastErrorCode() != 0) {
return FALSE;
}
return $this->count();
}

function read($id) {
$db = new SQLite3($this->get_file_name());
$tbl = $this->get_table_name();
$cmd = "SELECT * FROM $tbl WHERE ID = $id LIMIT 1";
$rs = $db->query($cmd);
if ($rs == FALSE) {
return FALSE;
}
$results = $rs->fetchArray(SQLITE3_ASSOC);
$db->close();
return $results;
}

function update($id, $special) {
$tbl = $this->get_table_name();
$cmd = "UPDATE $tbl SET";
$cols = $this->get_columns();
$bfirst = TRUE;
foreach ($cols as $col) {
if ($bfirst == FALSE) {
$cmd .= ", ";
}
$cmd .= " $col = '$special[$col]'";
$bfirst = FALSE;
}
$cmd .= " WHERE ID = $id";
echo "\n\n$cmd\n\n";
$db = new SQLite3($this->get_file_name());
$db->exec($cmd);
$db->close();
if ($db->lastErrorCode() != 0) {
return FALSE;
}
return TRUE;
}

function delete($id) {
$tbl = $this->get_table_name();
$cmd = "DELETE FROM $tbl WHERE ID = $id";
$db = new SQLite3($this->get_file_name());
$db->exec($cmd);
$db->close();
if ($db->lastErrorCode() != 0) {
return FALSE;
}
return TRUE;
}

}


So feel free to update:

get_columns()
get_table_name() [optional]
get_file_name() [optional]

Then simply use associative arrays as your "data access object" - as returned from the read($id) operation - then accessed via your own get_columns() names - to see how easily (ahem) CRUD happens!

The complete code + test case is here.

[ add comment ] ( 99 views )   |  permalink  |  related link
PyGame Example - The Lazy Star 
Had a chance to teach a bunch of wonderful new Python students this month.

Several were interested in using pygame, so we put together the following demonstration.

Thought we would share it.

Note that - before running pygame - that we will need to use pip (or pip3) to install the pygame package (e.g: pip3 install pygame)

Linux folks should install packages using PIP as to get those Super Cow Powers (i.e either su, or sudo should moo nicely.)

import pygame

pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Hackin' Around!")

back_color = (128, 45, 100) # Ubuntu Default

clock = pygame.time.Clock()

def stat(zEvent):
screen.fill(back_color)
if zEvent is None:
return
try:
loc = zEvent.__dict__['pos']
basicfont = pygame.font.SysFont(None, 72)
text = basicfont.render('*', True, (255, 0, 0), back_color)
screen.blit(text, loc)
except Exception as ex:
print("Exceptional:", zEvent)


stat(None)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT: # closing the window
break
stat(event)
pygame.display.update()
clock.tick(12) # fps
pygame.quit()

Note that 'fps' in the above stands for "frames per second." The lower, the slower. -You can set it to 1000 or so to speed things up ... allot!

Sharing is caring!

-Rn

p.s. If you want to learn more about programing in Python 3, then here is a discount coupon to my on-line training.

[ add comment ] ( 104 views )   |  permalink  |  related link
GUI, TUI, ... GTUI? 
Surely the fear of being labeled "old fashioned" can be a key motivator in the need to support any new technology?

Audio Reborn


Consider - for example - the former stigma long associated with "obsolete radio." --Surely "Modern TV" & video triumphed over that old, "obsolete" audio-only entertainment?

Yet rising from the stigma of being "old fashioned" entertainment, for example, allowed iPod to become the hottest product of a new millenia!

Indeed, while now surely supporting video as well, the mainstay of a global, billion-dollar, portable-player industry even presently revolves around simple, audio-only, music players.

(Got record player? -Even the collector's vinyl-market has been reborn!)

Text Reborn


In a like manner, we are seeing the beginning of a Renaissance in the use of console user-interfaces.

How can we say such a thing?

Well, long seen as being "old fashioned", the removal of textual / terminal support from Microsoft Windows - only to be resurrected in Windows 10 - underscored the trend.

Not only can one now use textual terminal emulation programs such as "curses" once again (remember "ansi.sys" or "vt100.sys"?), but a whole "next generation" of computer enthusiasts are busy writing seemingly text-only applications.

Codename: T.U.I


Surely many anticipated a probable resurgence of the Textual / Terminal User Interface (TUI) as a rising generation enjoyed the green-screen 'blinkage from the "Codename: Kids Next Door" episodes. A whimsical & enjoyable cartoons series, each episode proudly featured a TUI.

Herculean efforts over such programs as Dwarf Fortress have also been rewarded. (The author of this text-game has even been invited to contribute his source code to the Smithsonian!)

GUI - TUI?


So when terminal emulation / cursor positioning was officially removed from Microsoft Windows, allot of us knew that we had to rely upon API support.

Indeed, for quite some time we have taught others how to use the Windows Console API to create much the same effect... even under Visual Basic!

Other companies - such as Citrix - stepped up to fill the void so as to support million-dollar markets.

Yet while the flavor is decidedly console, savvy software developers know that just about any drawing surface supports textual renderings. By mapping pixels to mono-spaced fonts and / or de-kerened character-cells, even Java & Qt panels can be used to create a "GUI TUI!"

Hybrid TUI's


So into the realm of the Graphical Text User Interface, or "GTUI" ... (i.e. Decidedly TUI - but so much more!) do we find ourselves, today. Spear-headed by such innovations as the SDL, yet another 20-year effort is enjoying an ever-increasing popularity in the planet's new, cross-platform, GTUI marketplace.

Turbo Vision ... for GTUI!


Yet - having seen many such trends before - allow me to note that there remains ample time for anyone to anticipate - and intercept - where the GTUI market is all heading.

Surely, for those who want to yet earn their place on Wikipedia (or perhaps on Wallstreet?), the clear and present need is to provide support for a cross-platform "WIMP" ("Windows, Icons, Menus and Pointer") user interface in the GTUI realm.

Indeed, those who feel the GTUI-WIMP need, need not work uninspired! -Not only are Turbo Vision -style UI's still moving on just-fine, but even Python 3 has cool new projects (such as picotui) to help speed us on our way!


Conclusion


So while I toil away to create as much training as I can for my C/C++, Java, .NET, LAMP, AWS, Hadoop, and Python students, please allow me to alert you to what I am finding to be an extremely interesting trend. Just as the death of "radio" was far, far too readily predicted, so too has the ultimate demise of the TUI, been greatly exaggerated!


Sharing is caring,

-Randall


Oh... Yea... 'Lest we forget: IMO the king of the GTUI world surely must be libtcod. While somewhat of a PITA to build under C/C++ (over time, what isn't? =) wee Python devotees also may enjoin some relief there, as well.

Our Java friends might also take a look at Jexter!


[ add comment ] ( 92 views )   |  permalink  |  related link

<<First <Back | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | Next> Last>>