php - A better way to write MySQLI calls -


im new stackoverflow. understand question

at moment write mysqli calls - depends i'm trying achieve.

function getarticles($dbh) {     $query = "select article_id,article_name,article_text articles";     $result = mysqli_query($dbh,$query);     if(!mysqli_errno($dbh)) {         if(mysqli_num_rows($query) > 0) {             $articles = array();             while($rows = mysqli_fetch_object($query) {                 $articles[] = $rows;             }         }         mysqli_free_result($dbh)     } else {         echo mysqli_error($dbh);     }     return ($articles); } 

then fetch them , display using foreach() in calling page. can make mysql calls better in way?, or how write mysql calls.

i choose oo way too, apart that, wrap calling query in separate class or function. can write function takes sql query , array of parameters input, , returns array results or error code or error object (or array). way, functions getarticles, of have dozens, contain single line of code , don't have implement loop , error handling each time.

something this:

function executequery($dbh, $sql) {   $result = mysqli_query($dbh, $sql);   if ($result !== false)   {     while($row = mysqli_fetch_object($query) {       $data[] = $row;     }     return $data;   }   return false;     // or maybe return error code or error information?   // maybe throw exception?   // return array info, you'd have check    // if resulting array contains data or error information... }  function getarticles($dbh) {   return executequery(     $dbh,     "select article_id,article_name,article_text articles"); } 

see how pulls logic getarticles , generalizes in executequery?


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -