R
R
ReactiveSnaile2020-03-02 15:15:12
PHP
ReactiveSnaile, 2020-03-02 15:15:12

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:

spoiler

/**
     * Возвращает сортированный список задач с указанными идентификаторами
     * @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();


but something seems to me that there are more adequate options, what do you say?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question