有一些我不太明白的是,在
mysqli中准备和查询.
这一个是使用MysqLi :: query来处理查询,并且已经知道缺乏安全性:
public function fetch_assoc($query) { $result = parent::query($query); //$result = self::preparedStatement($query); if($result) { return $result->fetch_assoc(); } else { # call the get_error function return self::get_error(); # or: # return $this->get_error(); } }
这是一个具有prepare-bind-execute的,具有更好的安全性,我假设,
public function fetch_assoc_stmt($sql,$types = null,$params = null) { # create a prepared statement $stmt = parent::prepare($sql); # bind parameters for markers # but this is not dynamic enough... //$stmt->bind_param("s",$parameter); if($types&&$params) { $bind_names[] = $types; for ($i=0; $i<count($params);$i++) { $bind_name = 'bind' . $i; $$bind_name = $params[$i]; $bind_names[] = &$$bind_name; } $return = call_user_func_array(array($stmt,'bind_param'),$bind_names); } # execute query $stmt->execute(); # these lines of code below return one dimentional array,similar to MysqLi::fetch_assoc() $Meta = $stmt->result_Metadata(); while ($field = $Meta->fetch_field()) { $var = $field->name; $$var = null; $parameters[$field->name] = &$$var; } call_user_func_array(array($stmt,'bind_result'),$parameters); while($stmt->fetch()) { return $parameters; } # close statement $stmt->close(); }
但是,这两种方法都返回相同的结果,
$MysqLi = new database(DB_HOST,DB_USER,DB_PASS,DB_NAME); $sql = " SELECT * FROM root_contacts_cfm ORDER BY cnt_id DESC "; print_r($MysqLi->fetch_assoc_stmt($sql)); print_r($MysqLi->fetch_assoc($sql));
他们打印这个:
Array ( [cnt_id] => 2 [cnt_email1] => lau@xx.net [cnt_email2] => [cnt_fullname] => Lau T [cnt_firstname] => Thiam [cnt_lastname] => Lau [cnt_organisation] => [cnt_website] => [cnt_biography] => [cnt_gender] => [cnt_birthday] => [cnt_address] => [cnt_postcode] => [cnt_telephone] => [cnt_note] => [cnt_key] => [cat_id] => [tcc_id] => [cnt_suspended] => 0 [cnt_created] => 2011-02-04 00:00:00 [cnt_updated] => 2011-02-04 13:54:36 ) Array ( [cnt_id] => 2 [cnt_email1] => lau@xx.net [cnt_email2] => [cnt_fullname] => Lau T [cnt_firstname] => Thiam [cnt_lastname] => Lau [cnt_organisation] => [cnt_website] => [cnt_biography] => [cnt_gender] => [cnt_birthday] => [cnt_address] => [cnt_postcode] => [cnt_telephone] => [cnt_note] => [cnt_key] => [cat_id] => [tcc_id] => [cnt_suspended] => 0 [cnt_created] => 2011-02-04 00:00:00 [cnt_updated] => 2011-02-04 13:54:36 )
你应该注意到,在fetch_assoc_stmt的方法里面,我根本不用fetch_assoc.可能没有机会使用它作为准备使用不同的方式来返回结果.
所以,我的问题是使用prepare比查询更好,为什么要fetch_assoc存在?我们不应该只是忘记它,或者不应该PHP.net已经弃用? fetch_all是一样的 – 为什么我们应该把它放在第一位?
谢谢.