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 just started to practice coding in oop these days,
just wanted to ask if my code has a correct pattern.
i need your comments or suggestions so i can improve it,
thanks you guys for your patience and time.
here is my sample search code:

sample_class.php:

<?php
$host = 'localhost';
$db = 'sample_db';
$user = 'sample_user';
$pass = 'sample_password';
$conn = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
$conn->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:

<?php  
include('sample_class.php');
$search= new MySeachClass($database_connection);

if (isset($_POST['submit'])){  
$keyword = $_POST['keyword'];
$go_search = $search->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....
    }
}

<form action="" method="POST">  
<input type="text" name="keyword">  
<input type="submit" name="search">
</form>  
share|improve this question
add comment

2 Answers

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

share|improve this answer
add comment

The caller of MySearchClass methods should not know that there is a PDO access layer to database - the caller should not know about database at all! The class might internally query cache first or return hardcoded values - but return ready to use php collections (arrays)!

So I suggest moving all the fetchAll calls into MySearchClass methods.

share|improve this answer
add comment

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.