So I'm following a tutorial on Lynda.com regarding advanced PHP. They mention Late Static Bindings but I guess PHP 5.3 wasn't out when they made the tutorial so I'm trying to figure out how to do CRUD using a 'create' function in an extended class and pulling the attributes from the called class into the function. I feel like I'm missing something very simple, it insert a new row into my database, just no content. Heres the code, any suggestions would be useful.
PHP code in test.php file...
<?php
$user = new User();
$user->username = "johnsmith";
$user->password = "555";
$user->first_name = "john";
$user->last_name = "smith";
$user->create();
?>
User class that extends DatabaseObject class...
class User extends DatabaseObject {
protected static $table_name="users";
protected static $db_fields = array('id', 'username', 'password', 'first_name', 'last_name');
public $id;
public $username;
public $password;
public $first_name;
public $last_name;
}
DatabaseObject class with late static bindings...
class DatabaseObject {
protected static function attributes() {
$attributes = array();
foreach(static::$db_fields as $field) {
if(property_exists(get_called_class(), $field)) {
$attributes[$field] = get_called_class()->$field;
}
}
return $attributes;
}
protected static function sanitized_attributes() {
global $database;
$clean_attributes = array();
foreach(self::attributes() as $key => $value) {
$clean_attributes[$key] = $database->escape_value($value);
}
return $clean_attributes;
}
public static function create() {
global $database;
$attributes = self::sanitized_attributes();
$sql = "INSERT INTO ".static::$table_name." (";
$sql .= join(",", array_keys($attributes));
$sql .=") VALUES ('";
$sql .= join("', '", array_values($attributes));
$sql .= "')";
if($database->query($sql)) {
static::$id = $database->insert_id();// get last id saved in database and puts it in the id arguement
return true;
} else {
return false;
}
}