Answer the question
In order to leave comments, you need to log in
How to correctly form queries to the database in php?
Knowledgeable people, please take a look at how to do this correctly, tell me:
Records are displayed on the page, there are also three select inputs with options for sorting records, first new / old, stage of execution (7 options), users, you need to sort taking into account the values of all inputs, it turned out like this:
/**
* Возвращает сортированный список задач с указанными идентификаторами
* @param array $optionsArray <p>Массив с параметрами сортировки</p>
* @return array <p>Массив со списком задач</p>
*/
public static function getSortTasks($optionsArray)
{
// Соединение с БД
$db = Db::getConnection();
// Получаем опции для запроса
$direction = $optionsArray['direction'];
$work_status = $optionsArray['work_status'];
$contractor_id = $optionsArray['contractor_id'];
$work_status_sql = 'WHERE status = :status';
$contractor_id_sql = ' AND contractor_id = :contractor_id';
if($direction == 'new') $direction = 'DESC';
if($direction == 'old') $direction = 'ASC';
if($work_status == 'allstatus') $work_status_sql = '';
if($contractor_id == 'allcontractor') $contractor_id_sql = '';
if($work_status == 'allstatus' && $contractor_id != 'allcontractor') $contractor_id_sql = 'WHERE contractor_id = :contractor_id';
// Получение и возврат результатов
//$sql = "SELECT id, title, contractor_id, description, price, status, public FROM task WHERE status = :status AND contractor_id = :contractor_id ORDER BY id $direction";
$sql = 'SELECT id, title, contractor_id, description, price, status, public FROM task '.$work_status_sql. $contractor_id_sql.' ORDER BY id '.$direction;
// Используется подготовленный запрос
$result = $db->prepare($sql);
if($work_status != 'allstatus'){
$result->bindParam(':status', $work_status, PDO::PARAM_STR);
}
if($contractor_id != 'allcontractor'){
$result->bindParam(':contractor_id', $contractor_id, PDO::PARAM_INT);
}
// Выполнение коменды
$result->execute();
$tasksList = array();
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question