<? /** * @example */
// assume we have a database named test at localhost, with user foo:bar // structure: // ------------ // // CREATE TABLE `test`.`bar` ( // `id` int( 11 ) NOT NULL AUTO_INCREMENT , // `name` varchar( 255 ) NOT NULL default '', // `added` datetime NOT NULL default '0000-00-00 00:00:00', // `desc` text NOT NULL , // PRIMARY KEY ( `id` ) // ); // // ------------ //define connection data $data = array ( "host" => "localhost", "user" => "foo", "pass" => "bar", "db" => "test", ); //avoid annoing inclusion statements function __autoload($name) { require_once("class.$name.php"); } //start the db engine DbHandler::connect($data); //we may want to extend the default DbObject class class DbFoo extends DbObject { //required to define... it's the table we will use protected $table = "bar"; //add new foo public function add($name) { $foo = new DbFoo; $foo->name = $name; $foo->added = 'NOW()'; $foo->save(); unset($foo); } } //initialize foo $test = new DbFoo(); //define new foo $test->name = "preston"; $test->desc = "the pig"; $test->added = "NOW()"; //save to database $test->save(); //add new 1337 foo using custom DbFoo::add() function $test->add("1337"); //let's try searching what we have just added.. $c = new DbCriteria(); $c->add("name", "prest%", "like"); $c->add("added", "NOW()", "<", "and"); $c->add("desc", null, "!=", "and"); //get foo by criteria $test->get($c); echo $test->name; //should output "preston" echo $test->desc; //should output "the pig" //now lets try advanced criterias
//id should be 2, 3 or 5 $c2 = new DbCriteria(); $c2->addIn("id", array(2, 3, 5)); //name should be preston and desc shoud be like pig $c3 = new DbCriteria(); $c3->add("name", "preston"); $c3->add("desc", "%pig%", "like", "and"); //now let's combine these two criterias with OR $c = new DbCriteria(); $c->combine($c2, $c3, "or"); //..and define order by name desc and limit 0, 3 $c->addOrder("name", "desc"); $c->addLimit(0, 3); //now let's get the objects which meet these criterias $results = $test->getMultiple($c); //and print them out foreach ($results as $result) echo $result->id . " " . $result->name . "<br>";
//we can use DbObject without extending it too.. But you shouldn't though.. $foo = new DbObject("bar"); $foo->name = "jedi"; $foo->added = "CURDATE()"; //we will overwrite some other object with info above.. and we'll do this by criteria where name = preston $c = new DbCriteria(); $c->add("name", "preston"); $foo->save($c);
//see if the save worked.. $bar = new DbFoo(); $c = new DbCriteria(); $c->add("name", "jedi"); $jedi = $bar->get($c, array("name", "desc")); echo $jedi->desc . " is named " . $jedi->name; //should output "the pig is named jedi" //this whole thingie is only v0.1.. still, it should be enough to complete something simple.. though i hope to improve it in future. any ideas? mail me: tomas@netatbiz.com //enjoy! ?>
|