我有一个类命名用户,其代码如下
require_once(LIB_PATH.DS.'database.php');
class User extends DatabaseObject {
protected static $table_name="users";
public $id;
public $username;
public $password;
public $first_name;
public $last_name;
}
我从一个DatabaseObject类中扩展了这个User类,我刚刚在下面创建了一个Create方法,我为数据库CRUD提供了常用的方法是我的DatabaseObject类
require_once(LIB_PATH.DS.'database.php');
class DatabaseObject {
public static function attributes() {
$class_name = get_called_class();
$object = new $class_name;
return get_object_vars($object);
}
public static function sanitized_attributes() {
global $database;
$clean_attributes = array();
foreach(static::attributes() as $key => $value){
$clean_attributes[$key] = $database->escape_value($value);
}
return $clean_attributes;
}
public static function create() {
global $database;
$attributes = static::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)) {
return $sql;
} else {
return false;
}
}
}
当我从test.php运行测试时,检查Create是否有效 使用此代码
$user = new User();
$user->username = "johnsmith";
$user->password = "abcd12345";
$user->first_name = "John";
$user->last_name = "Smith";
echo User::create();
它只返回带有空值的查询
INSERT INTO users
(id, username, password, first_name, last_name) VALUES ('', '', '', '', '')
当我检查phpmyadmin时插入一行但是空值是什么,这是我正在制作的错误请帮助
此致
Tapos
答案 0 :(得分:1)
您的create()
函数是static
,因此它与您正在处理的实例没有关联。
然后,您的sanitized_attributes()
会创建类[$object = new $class_name;
]的无关实例,并对其属性进行迭代,根据定义,这些属性为空。
顺便说一下,用户准备了凌乱的字符串连接操作语句:PDO
正等着你!
答案 1 :(得分:0)
将您的方法更改为public
删除static关键字,并使用下面的代码将指针引用传递给create方法
$user = new User();
$user->username = "johnsmith";
$user->password = "abcd12345";
$user->first_name = "John";
$user->last_name = "Smith";
echo $user->create($user);
当您将对象传递给thye create方法时,其余代码将如下所示
public function attributes(&$obj) {
return get_object_vars($obj);
}
public function sanitized_attributes(&$obj) {
global $database;
$clean_attributes = array();
foreach($obj->attributes($obj) as $key => $value){
$clean_attributes[$key] = $database->escape_value($value);
}
return $clean_attributes;
}
public function create(&$obj) {
global $database;
$attributes = $obj->sanitized_attributes($obj);
$sql = "INSERT INTO ".static::$table_name." (";
$sql .= join(", ", array_keys($attributes));
$sql .= ") VALUES ('";
$sql .= join("', '", array_values($attributes));
$sql .= "')";
if($database->query($sql)) {
} else {
return false;
}$obj->sanitized_attributes($obj);
}
希望这有效!