HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Search form sample pattern

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
formsamplepatternsearch

Problem

I've just started to practice coding in OOP and just wanted to ask if my code's pattern is correct. I need your comments or suggestions so I can improve it.

sample_class.php:

setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);  

Class MySearchClass {

    public function __construct(PDO $conn) {
        $this->pdo=$conn;  
    }

    public function search_name($keyword){

        $query = "SELECT * FROM table WHERE name = '$keyword'";  
        $result = $this->pdo->prepare($query);  
        $result ->execute();  

        return $result;
    }

    public function view_all(){
        $query = "SELECT * FROM table";  
        $result = $this->pdo->prepare($query);  
        $result ->execute();  

        return $result;
    } 
}


search_form.php:

search_name($keyword);

    $data = $go_search->fetchAll(PDO::FETCH_ASSOC);   

    foreach($data as $row){
        echo $row['name'];  
        echo other rows....
    }  

}else{
    $view = $search->view_all();
    $data = $view->fetchAll(PDO::FETCH_ASSOC);  

    foreach($data as $row){
        echo $row['name'];  
        echo other rows....
    }
}

  
  

Solution

Here's a recommendation to bind parameters correctly. This sort of thing is used to prevent against SQL injection attacks.

$query = "SELECT * FROM table WHERE name = :keyword";  
$statement = $this->pdo->prepare($query);
$statement->bindParam(':keyword', $keyword, PDO::PARAM_STR);
$result $statement->execute();


Read more about PDOStatement#bindParam here

Code Snippets

$query = "SELECT * FROM table WHERE name = :keyword";  
$statement = $this->pdo->prepare($query);
$statement->bindParam(':keyword', $keyword, PDO::PARAM_STR);
$result $statement->execute();

Context

StackExchange Code Review Q#19551, answer score: 5

Revisions (0)

No revisions yet.