According to this thread: https://codereview.stackexchange.com/questions/29362/very-simple-php-pdo-class people generally say it’s stupid to create custom PDO query handlers, which I find very hard to understand.
For instance, in my projects I prefer to have a class / function to do things I do all the time, quicker for me.
For instance, when you need to perform simple updates in a table, I have created this function, which I use all the time:
function UpdateData($table, $data, $where, $params=array()) { $sql = 'UPDATE `' . tbl_prefix.$table . '` SET '; foreach($data as $name => $value) { $params[':' . $name] = $value; $runs++; $sql .= "`$name` = :" . $name; if(end($data) !== $value) // if not last run $sql .= ','; } if(!is_array($where)) { $sql .= ' ' . $where; // insert where clause } else { // Array format can be used $sql .= ' WHERE'; foreach($where as $argument => $value) { $params[':where_'.$argument] = $value; $num++; $sql .= " `" . $argument . "` = :where_" . $argument . " "; if(end($where) !== $value) $sql .= ' AND'; } } $query = doQuery($sql, $params); // do the update if($query) return true; }
And the doQuery
(which I also use when I want to query database):
function doQuery($query, $params=array()) { global $db; try { $result = $this->$db->prepare($query); $result->execute($params); $result->setFetchMode(PDO::FETCH_ASSOC); return $result; } catch(PDOException $ex) { $real_query = $query; foreach($params as $name => $value) { $real_query = str_replace($name, '''.$value.''', $real_query); } SystemLog($ex->GetMessage(), array('real_query' => $real_query, 'query' => $query), 1); // log error } return false; }
Is there anything wrong with this? I find it extremely useful.
some code have been taken out of the scripts to simplify the code
Advertisement
Answer
I think what you’re doing is fine. The main argument in that thread is that you miss out on Prepared statements: I’ve been using SQL since about 1984 and DBMS’s have been good enough that using a Prepared statement makes no real difference since probably 1994. I haven’t used one for over 20 years and my systems do perform properly.
Still, everybody has their own opinion. I’ve done what you do many times and never had a problem with it. Nowadays I use ORM’s which means I don’t have to do that either.