PDO:使执行语句动态...但不起作用

时间:2014-04-24 16:21:49

标签: php pdo

这应该很容易......但我无法弄明白。如果以下execute语句在插入查询结束时有效.....

     $query->execute(array($this->visible_password, 
                           $this->hashed_password, 
                           $this->temp_hashed_password, 
                           $this->first_name, 
                           $this->last_name, 
                           $this->position, 
                           $this->location, 
                           $this->city, 
                           $this->email, 
                           $this->country, 
                           $this->institution, 
                           $this->interests, 
                           $this->profile_comment));

       $result =  join(", ", array_values($place_holder));
       echo $result;

给出

$ this-> visible_password,$ this-> hashed_pa​​ssword,$ this-> temp_hashed_pa​​ssword,$ this-> email,$ this-> first_name,$ this-> last_name,$ this-> position,$ this-> location,$ this-> city,$ this-> country,$ this-> institution,$ this-> interests,$ this-> profile_comment

然后为什么这不起作用.....

     $query->execute(array($result))

占位符上的var_dump给出了......

   array(13) { 

 [0]=> string(26) "$this->visible_password" 
 [1]=> string(25) "$this->hashed_password" 
 [2]=> string(30) "$this->temp_hashed_password" 
 [3]=> string(15) "$this->email" 
 [4]=> string(20) "$this->first_name" 
 [5]=> string(19) "$this->last_name" 
 [6]=> string(18) "$this->position" 
 [7]=> string(18) "$this->location" 
 [8]=> string(14) "$this->city" 
 [9]=> string(17) "$this->country" 
 [10]=> string(21) "$this->institution" 
 [11]=> string(19) "$this->interests" 
 [12]=> string(25) "$this->profile_comment" }

$ placeholder是一个数组...它接受类

的属性($ attributes)
            $place_holder = array();
            foreach ($attributes as $key => $value) {
            $place_holder[] = "&#36this->" . $key;
        }

我一直在尝试在我的用户类抽象中创建用户方法,所以我可以在我的所有类中使用它。我从mysqli(噩梦)将我的网站转换为PDO。这是方法......

public function  pdo_create_test() {

  $attributes = $this->attributes();
  $att = array_keys($attributes);     
   $question_marks = array();
    foreach ($attributes as $key => $value) {
            $question_marks[] = "?";
    }
   $place_holder = array();
    foreach ($attributes as $key => $value) {
           $place_holder[] = "&#36this->" . $key;
        }
  $result = join(", ", array_values($place_holder));
  $sql = "INSERT INTO ".self::$table_name." (";
  $sql .= join(", ", array_keys($attributes));
  $sql .= ") VALUES (";
  $sql .= join(", ", array_values($question_marks));
  $sql .= ")";
  $query = $handler->prepare($sql);
  $query->execute(array($this->visible_password, 
                      $this->hashed_password, 
                      $this->temp_hashed_password, 
                      $this->first_name, 
                      $this->last_name, 
                      $this->position, 
                      $this->location, 
                      $this->city, 
                      $this->email, 
                      $this->country, 
                      $this->institution, 
                      $this->interests, 
                      $this->profile_comment));

                   }

这是一个更新....(我已经更改了占位符以获取值,如下面Bill所说) 我也回应了sql和占位符的结果,看看是什么。

public function  pdo_create_test() {
  global $handler;
  $attributes = $this->attributes();
  $att = array_keys($attributes);
  $question_marks = array();
    foreach ($attributes as $key => $value) {
    $question_marks[] = "?";
    }
  $place_holder = array();
    foreach ($attributes as $key => $value) {
    $place_holder[] = $this->$key;
        }
  $result = join(", ", array_values($place_holder));
  $sql = "INSERT INTO ".self::$table_name." (";
  $sql .= join(", ", array_keys($attributes));
  $sql .= ") VALUES (";
  $sql .= join(", ", array_values($question_marks));
  $sql .= ")";
    echo $sql;
    echo "<br/>";
    echo "<br/>";
    echo $result;
    $query = $handler->prepare($sql);
    $query->execute(array($result));

}

代表

             $user = new User;
             $user->visible_password = "Sam";
             $user->hashed_password = "Walsh";
             $user->pdo_create_test();

输出

INSERT INTO用户(visible_password,hashed_pa​​ssword,temp_hashed_pa​​ssword,email,first_name,last_name,position,location,city,country,institution,interests,profile_comment)VALUES(?,?,?,?,?,?,?,? ,?,?,?,?,?)

Sam,Walsh ,,,,,,,,,,,,

但没有进入数据库....不明白为什么......其他数据库字段设置为NULL所以这不是一个问题......

2 个答案:

答案 0 :(得分:1)

PHP确实具有variable variables的概念,因此您可以这样做:

$varname = 'foo';

$foo = 123;

echo $$varname;

但这个功能有限。您不能将它应用于数组的所有元素,也不能将它与$this->foo符号用于对象变量。

您可以使用变量变量语法以这种方式获取与属性对应的对象变量的

$place_holder = array();
foreach ($attributes as $key => $value) {
    $place_holder[] = $this->$key;
}

请注意$key之后的->。通常,对象变量语法在该位置没有$。通过在那里使用$,我告诉它获取名称为$key的值的对象变量的值。

顺便说一下,这是一种更简洁(也可能更快)的方式来做同样的事情:

$place_holder = array_intersect_key($attributes, get_object_vars($this));

重新评论:

嗯,首先,你做错了:

$result = join(", ", array_values($place_holder));

这会生成一个字符串,其值以逗号分隔。如果将它包装在array($result)中,它只是创建一个单个字符串的数组,即使单个字符串包含逗号,也没有关系。

换句话说,这两个数组完全不同:

array('A,B,C') // array with one element

array('A', 'B', 'C') // array with three elements

相反,您需要传递给execute()是一个数组,其元素数量与?占位符的数量相同。

所以请传递一下:

$query->execute($place_holder);

其次,您需要在每prepare()execute()之后检查错误:

if (($query = $handler->prepare(...)) === false) {
  print_r($handler->errorInfo());
}
if ($query->execute($result) === false) {
  print_r($query->errorInfo());
}

或者,如果编码过多,您可以改为enable PDO exceptions,错误会导致您的应用因错误而终止。

$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

答案 1 :(得分:0)

我不确定你的place_holder变量包含什么,但我认为这可能就是原因。 Join只是implode函数的另一个名称,它返回一个字符串。执行需要实际的物理输入项。

execute上的PHP站点获取输入值数组:

  

具有与绑定参数一样多的元素的值数组   在正在执行的SQL语句中。所有值均视为   PDO :: PARAM_STR。

<强>更新

如注释中所述,这是一个使用给定数据对象执行SQL字符串的函数。最好将它分成几个函数(创建参数数组,绑定参数等),但为了便于阅读,我将它们全部放在一个函数中。

该功能的示例用法可以是executeQuery('SELECT * FROM users WHERE id = :id', array('id' => 1));

function executeQuery($sql, $data) {
    //Assumed that $pdo is created and is a valid PDO object
    $params = array();
    preg_match_all('/:\w+/', $sql, $matches);
    //Loop through all the matches
    //Create an array that looks like: array(
    //  :id => 1, 
    //  :name => 'Me'
    //)
    foreach($matches[0] as $param) {
        $paramName = substr($param, 1);
        //If the item is not supplied in the data object, null will be used
        $params[$param] = isset($data[$paramName]) && !empty($data[$paramName]) ? $data[$paramName] : null;
    }
    //Pepare the SQL statement
    if(($stmt = $pdo->prepare($sql)) !== false) {
        //Bind all parameters
        foreach($params as $param => $value) {
            $stmt->bindValue($param, $value);
        }
        //Execute the statement
        $stmt->execute();
    }
}
相关问题