【问题标题】:PHP OOP binding problem inside the method方法内部的PHP OOP绑定问题
【发布时间】:2020-09-24 20:13:36
【问题描述】:

我非常努力地使用类内部的准备、绑定和执行来创建此方法。但我想我对它没有足够的了解,无论我做什么,我都无法让它发挥作用。我在谷歌上找了几个小时。我知道下面的代码关于绑定是错误的,但是有人可以告诉我在此方法中进行绑定的正确方法吗?

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

【问题讨论】:

  • 而不是绑定 - 你试过if ($stmt->execute($fields)) {
  • @NigelRen 如果我只是在执行中传递 $fields,我将如何通过 $params=[ ] ?
  • 如果您使用的是bindValue,则无需在foreach 中使用&
  • foreach ($fields as $field => &$params) 没有意义。 $fields 是字符串,不是数组。
  • $params是函数参数,你为什么要用它作为迭代变量?

标签: php pdo


【解决方案1】:

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

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

【讨论】:

  • 你在调用bindValue()时没有使用$type
  • 不需要使用引用变量&$value
  • 如果您不确定这是否正确,应该在问题中,而不是答案中。
  • 谢谢。他们不允许我问一个我不知道为什么的问题
  • 我的意思是您应该编辑您的原始问题并将其添加到其中。
猜你喜欢
  • 2014-04-18
  • 2014-07-18
  • 2011-05-07
  • 1970-01-01
  • 2022-01-10
  • 1970-01-01
  • 2012-09-20
  • 1970-01-01
相关资源
最近更新 更多