Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have the following functions:

 function getExample($id, $otherid) {
            global $db;
            $query = 'SELECT * FROM examples WHERE id = :id AND otherid= :otherid';
            try { 
                $statement = $db->prepare($query);
                $statement->bindValue(':id', $id);
                $statement->bindValue(':otherid', $otherid);
                $statement->execute();
                $result = $statement->fetchAll();
                $statement->closeCursor();
                return $result;
            } catch (PDOException $e) {
                $error_message = $e->getMessage();
                display_db_error($error_message);
            }
        }

 function getSecExample($id) {
            global $db;
            $query = 'SELECT * FROM examples WHERE id= :id';
            try { 
                $statement = $db->prepare($query);
                $statement->bindValue(':id', $id);
                $statement->execute();
                $result = $statement->fetchAll();
                $statement->closeCursor();
                return $result;
            } catch (PDOException $e) {
                $error_message = $e->getMessage();
                display_db_error($error_message);
            }
        }

Is there a way to make this one function instead of two? I want it to be secure and done with the best practices.

share|improve this question

1 Answer 1

I'm not sure why you think that forcing this into one function will make it a "best practice," and that doesn't seem right anyways.

I suppose one way you could do it is:

 WHERE id = :id AND otherid LIKE :otherid

If it were to be in the second function, :otherid would be a wildcard (%). Otherwise just have your value. Check out this.

share|improve this answer
    
The reason I was asking, is because I have a lot of functions like that; they are quite a bit the same. I was hoping to somehow combine some of them together so I had less functions to deal with. I appreciate your response. –  Sam J. Feb 16 at 18:45

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.