Einzelnen Beitrag anzeigen

Benutzerbild von Valle
Valle

Registriert seit: 26. Dez 2005
Ort: Karlsruhe
1.223 Beiträge
 
#32

AW: [PHP] Klassenstruktur für Adressdatenbank

  Alt 11. Feb 2012, 14:35
Ups, jetzt hab ich dich fast vergessen.

Zum mysql_select_db: Schau doch einfach selbst nach wie das geht? Wink mit Zaunpfahl.

Jedenfalls hab ich hier mal eine kleine Herausforderung für dich. Sag Bescheid wenn du etwas nicht verstehst. Der schöne Teil des Codes sind die zwei letzten Zeilen unten. Diese zeigen, wie man später mit Datenbanken (im Controller) arbeiten kann. Selbstverständlich lässt sich das alles noch erweitern. Die Save Methode ist nicht vollständig und auch nicht getestet, da ich jetzt leider weg muss. Ich wollte dir den Code nur nicht vorenthalten. Du brauchst mindestens PHP 5.3 für das "Late static Binding" (get_called_class).

PHP-Quellcode:
abstract class DB_Table
{

    static protected $table = NULL;

    protected $fields = array();
    protected $changed = array();
    protected $exists = false;

    public function __construct(array $fields, $exists = false)
    {
        $this->fields = $fields;
        $this->exists = $exists;
    }

    public function __get($name)
    {
        return $this->fields[$name];
    }

    public function __set($name, $value)
    {
        if ($name == "id")
            throw Exception("Cannot changed ID. Yet.");
        array_push($this->changed, $name);
        return $this->fields[$name] = $value;
    }

    public function save()
    {
        if ($this->exists and count($this->changed) > 0) {
            $sql = array();
            foreach ($this->changed as $column) {
                $sql[] = "`" . $key . "` = '" . mysqli_real_escape_string($this->fields[$column]) . "'";
            }
            $sql = "UPDATE `" . $this->table . "` SET " . implode(", ", $sql) . " WHERE `id` = " . intval($this->fields['id']);
            print($sql);
        } else {
            // TODO Insert
        }
    }

    /**
    * Returns one instance with primary key = $id
     */

    
    public static function get($id)
    {
        $class = get_called_class();

        if ($class == __CLASS__)
            throw new Exception("Cannot call get() directly.");

        $result = mysql_query("SELECT * FROM `" . $class::$table . "` WHERE `id` = " . intval($id));
        return $class::getOne($result);
    }

    protected static function getOne($result)
    {
        $class = get_called_class();

        if ($result === false)
            throw new Exception("Query faild. " . mysql_error() . " (" . mysql_errno() . ")");
        if (mysql_num_rows($result) == 0)
            throw new Exception("No object matching id " . str($id));
        if (mysql_num_rows($result) > 1)
            throw new Exception("Too many results. Please check table schema.");

        return new $class(mysql_fetch_assoc($result), true);
    }

    protected static function getMultiple($result)
    {
        $class = get_called_class();

        if ($result === false)
            throw new Exception("Query faild. " . mysql_error() . " (" . mysql_errno() . ")");
        if (mysql_num_rows($result) == 0)
            throw new Exception("No object matching id " . str($id));

        $list = array(); // TODO Verwaltungsklasse für mehrere Reihen!
        while ($row = mysql_fetch_assoc($result)) {
            $list[] = new $class($row, true);
        }
        return $list;
    }


}

class DB_Adressen extends DB_Table
{
    
    static protected $table = 'adressen';

    public function findByName($name)
    {
        $name = mysql_real_escape_string($name);
        $result = mysql_query("SELECT * FROM adressen WHERE name = '" . $name . "'");
        return self::getMultiple($result);
    }

}

mysql_connect("127.0.0.1", "", "");
mysql_select_db("test");

var_dump(DB_Adressen::get(1));
var_dump(DB_Adressen::findByName("Puff"));
Liebe Grüße,
Valentin
Valentin Voigt
BOFH excuse #423: „It's not RFC-822 compliant.“
Mein total langweiliger Blog
  Mit Zitat antworten Zitat