KillGorack Posted October 23, 2021 Share Posted October 23, 2021 (edited) Simple code but has a lot of if then statements.. can it be simplified somehow? within a database class. function columninfo($table, $col = NULL) { if($this->CheckTable($table)){ if($col == NULL){ $err = false; }elseif($this->Checkfield($table, $col)){ $err = false; }else{ $err = true; } if($err == false){ $stmt = $this->db->prepare('SELECT * FROM '.$table); $stmt->execute(); $numCol = $stmt->columnCount(); $rtrn = array(); for ($i = 0; $i < $numCol; $i++) { if($col == NULL || $stmt->getColumnMeta($i)['name'] == $col){ $rtrn[] = $stmt->getColumnMeta($i); } } if(count($rtrn) == 1){ $rtrn = $rtrn[0]; } return $rtrn; }else{ return false; } }else{ return false; } } <edit> Sorry if the second parameter is left out, just return info on all the columns. If it's supplied return for just that column. </edit> Edited October 23, 2021 by KillGorack Quote Link to comment https://forums.phpfreaks.com/topic/314094-simplify-code/ Share on other sites More sharing options...
requinix Posted October 23, 2021 Share Posted October 23, 2021 Suggestion #1: if ($condition) { // ... } else { return $value; } // is the same as if (!$condition) { return $value; } // ... Suggestion #2: if ($condition_1) { // thing } else if ($condition_2) { // same thing } // is the same as if ($condition_1 || $condition_2) { // thing } I have two more, but let's start with those and see what you do. Quote Link to comment https://forums.phpfreaks.com/topic/314094-simplify-code/#findComment-1591368 Share on other sites More sharing options...
Solution Psycho Posted October 25, 2021 Solution Share Posted October 25, 2021 Here 0is how I would handle that function columninfo($table, $col = NULL) { //State the error condition check if(!$this->CheckTable($table)){ return false; } //State the error condition check if($col!=NULL && !$this->Checkfield($table, $col)){ return false; } //No errors $stmt = $this->db->prepare('SELECT * FROM '.$table); $stmt->execute(); $numCol = $stmt->columnCount(); $colAry = array(); for ($i = 0; $i < $numCol; $i++) { if($stmt->getColumnMeta($i)['name'] == $col) { //Return type for selected column return $stmt->getColumnMeta($i)[0]; } else { //Append current column to return arrray $colAry[] = $stmt->getColumnMeta($i); } } //Return array for all columns return $colAry; } Quote Link to comment https://forums.phpfreaks.com/topic/314094-simplify-code/#findComment-1591382 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.