首页 > 解决方案 > 方法内部的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;
        }
    }

标签: phppdo

解决方案


所以我制作了这样的代码进行绑定。我不知道这是否是正确的方法。我知道我一直在改变东西。我想这是学习尝试不同事物的最佳方式。

//$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;
}

推荐阅读