php - 方法内部的PHP OOP绑定问题
问题描述
我非常努力地使用类内部的准备、绑定和执行来创建此方法。但我想我对它没有足够的了解,无论我做什么,我都无法让它发挥作用。我在谷歌上找了几个小时。我知道下面的代码关于绑定是错误的,但是有人可以告诉我在这个方法中进行绑定的正确方法吗?
class User {
protected static $db_table = "users";
protected static $db_table_fields = array('username', 'password', 'first_name', 'last_name');
public $id;
public $username;
public $password;
public $first_name;
public $last_name;
protected function properties() {
$properties = array();
foreach (static::$db_table_fields as $db_field) {
if (property_exists($this, $db_field)) {
$properties[$db_field] = $this->$db_field;
}
}
return $properties;
}
protected function clean_properties() {
global $database;
$clean_properties = array();
foreach ($this->properties() as $key => $value) {
$clean_properties[$key] = $value;
}
return $clean_properties;
}
public function create($params= []){
global $database;
$properties = $this->clean_properties();
$fields = ":" . implode("',:'", static::$db_table_fields);
$sql= "INSERT INTO " .static::$db_table . "(" . implode(",", array_keys($properties)) . ")
VALUES('". $fields ."')";
$stmt = $database->prepare($sql);
foreach ($fields as $field => &$params) {
$stmt->bindValue($field, $params);
}
if ($stmt->execute()) {
$this->id = $database->InsertId();
return true;
} else {
return false;
}
}
解决方案
所以我制作了这样的代码进行绑定。我不知道这是否是正确的方法。我知道我一直在改变东西。我想这是学习尝试不同事物的最佳方式。
//$param = array('x'=>$x, 'y'=>$y);
public function bind($param = [], $type=NULL){
foreach($param as $key=>&$value){
if (is_null($type)) {
switch (true) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
$this->stmt->bindValue(':'.$key,$value);
}
return $this->stmt;
}
推荐阅读
- http - 通过 http 显示的 Gstreamer 和 hlssink 不起作用
- python - 找到一个集合(具有元素的副本)是python中更大集合的子集
- higher-order-functions - 流氓:函数可以返回函数吗
- javascript - 从数组中删除字符串
- recursion - 防止在 Common Lisp 中重复调用递归函数
- linux - 如何使用安装 openssl 从源代码重新配置 Apache?
- rust - 为什么这个 TextureCreator 实例没有
活得够长吗? - c++ - 使用带有指针的 new 时创建指定长度的数组
- javascript - 如何在javascript中设置上午/下午
- android - 如何将 CheckBox buttonDrawable 重置为默认值