I'm new to this PDO PHP and I have coded this spaghetti style. I hope you can give me idea how to improve using prepared statements. I'm not a lazy person, but I really need your help to improve my coding style.
try {
$select = "SELECT users.id, users.users_id, username, firstname, lastname, password, position";
$from = " FROM users
INNER JOIN users_role
ON users.id=users_role.users_id
INNER JOIN role
ON users_role.users_role=role.id";
$where = " WHERE";
$placeholders = array();
if ($category !=''){
if ($category == 'admin'){
$where .= " position='admin'";
if ($character_match !=''){
$where .= " AND ";
}
}
else if($category == 'instructor'){
$where .= " position='Instructor'";
if ($character_match !=''){
$where .= " AND ";
}
}
else if ($category=='student'){
$where .= " position='student'";
if ($character_match !=''){
$where .= " AND ";
}
}
elseif ($category == 'Unverified'){
$where .= " position='Unverified'";
}
else if ($category == 'view_all') {
$where = "";
if ($character_match != ''){
$where = " WHERE ";
}
}
if($character_match !=''){
$where .= "(username LIKE '" . $character_match . "%'"
. " OR firstname LIKE '" . $character_match . "%'"
. " OR lastname LIKE '" . $character_match . "%')";
$placeholders[] = $character_match;
}
$where .= " ORDER BY position ASC";
$sql = $select . $from . $where;
$q = $this->db->prepare($sql);
$q->execute($placeholders);
}
}
catch(PDOException $e){
$e->getMessage();
}
$rows = array();
while($row = $q->fetch(PDO:: FETCH_ASSOC)){
$rows[] = $row;
}