PHP and PDO dynamic parameter binding -
i'm trying fix butchered bit of code - might have guessed, i'm cocking bind param syntax. in fact, i'm not sure i'm trying possible. here's class method...
/*** * * @select values table * * @access public * * @param string $table name of table * * @param array $fieldlist fields return in results, defaults null * * @param array $criteria search criteria keyed fieldname * * @param int $limit limit of records return, defaults 10 * * @return array on success or throw pdoexception on failure * */ public function dbsearch($table, $fieldlist = null, $criteria = null, $limit = 10) { // setup $this->db point pdo instance $this->conn(); // build fieldlist if( is_null($fieldlist) or !is_array($fieldlist) or count($fieldlist) == 0) { $returnfields = '*'; } else { $returnfields = "'".implode("', '", $fieldlist)."'"; } // build criteria if( is_null($criteria) or !is_array($criteria) or count($criteria) == 0) { $whereclause = ''; } else { $whereclause = array(); foreach ($criteria $key => $value){ $bind_name = 'bind_'.$key; //generate name bind1, bind2, bind3... $$bind_name = $value; //create variable name value in $bind_names[] = & $$bind_name; //put link variable in array $whereclause[] = "'$key' = :$bind_name"; } $whereclause = count($whereclause) > 0 ? ' '.implode( ' , ' , $whereclause ) : ''; } $sql = "select $returnfields '$table' $whereclause limit $limit"; $stmt = $this->db->prepare($sql); if( $whereclause != '') { call_user_func_array(array(&$stmt, 'bindparam'), $bind_names); } $stmt->execute(); return $stmt->fetchall(pdo::fetch_assoc); }
... @ point want call using along these lines...
// users in database... $user_recs = $crud->dbsearch('user', array('user_name'), array('user_name'=> $_post['username'])); $users = $user_recs->fetchall(pdo::fetch_assoc);
how bonkers this? possible? need pass in param types somehow? gratefully received!
i don't understand how function better conventional
$stmt = $db->prepare("select user_name user user_name = ?"); $stmt->execute($_post['username']); $users = $stmt->fetchall();
mind you,
- it keeps query flexible.
limit ?,?
possible - it keeps query readable. natural english of sql stays in place. still can tell query do, without need of learning brain-damaging language. side effect, other developer can comprehend code too.
Comments
Post a Comment