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:
<?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>
3 Answers 3
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
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.
If you're on PHP 5.2.0 you should also use filter_input_array or filter_input() rather than $_POST as this allows you to sanitize the string before it goes anywhere else.
For example:
$post_copy = filter_input_array(INPUT_POST, FILTER_SANITIZE_SPECIAL_CHARS);
or
$keyword = filter_input(INPUT_POST, 'keyword', FILTER_SANITIZE_SPECIAL_CHARS);
Using the filter_input_array can also allow you to specify what items you expect in the $_POST as items and apply a filter on them. This basically means if someone sends junk to you in the $_POST it will also be filtered out.