简体   繁体   中英

PHP - Using functions to write SQL Query

Folks, I'm writing a query for a report and since it has a lot of parameters, I decided to write a few functions for it (suggestions are welcome).

In one of my where clauses, I wrote a function that will write the beginning of the clause, then write every item in my array and then close the clause below. This is the function:

function checkStatuses() {
    global $status;
    echo " tl.task_log_status in (";
    foreach ($status as $option) {
        echo "'$option', ";
    }
    echo "'60') AND";
}

Below is my query:

$sql = "SELECT co.company_name as EMPRESA,
    p.project_name as PROJETO,
    p.project_code as CODIGO,
    tk.task_name as TAREFA,
    concat(c.contact_first_name,' ',c.contact_last_name) as USUARIO,
    DATE_FORMAT(tl.task_log_date, '%d/%m/%Y') as DATA,
    tl.task_log_description as DESCRICAO,
    tl.task_log_hours as HORAS_REPORTADAS,
    tl.task_log_costcode as CODIGO_CUSTO
FROM dotp_task_log tl, dotp_companies co, dotp_tasks tk, dotp_projects p, dotp_users u, dotp_contacts c
WHERE tk.task_id = tl.task_log_task
AND 
    p.project_id = tk.task_project
AND 
    u.user_id = tl.task_log_creator
AND 
    c.contact_id = u.user_contact
AND 
    co.company_id = p.project_company
AND
    co.company_id = $company 
AND
    $project_code 
AND 
    $status_code 
    tl.task_log_date BETWEEN '$initial_date' AND '$end_date'
ORDER BY
    tl.task_log_date";

Right below this code I echoed $sql to see what's going on, and it shows like this:

tl.task_log_status in ('0', '1', '3', '2', '60') ANDSELECT co.company_name as EMPRESA,
        p.project_name as PROJETO,
        p.project_code as CODIGO,

As you can see, the where clause is being written before the rest of the $sql variable. Why's that? In my example, I declared variable $status_code = checkStatuses(); , but that didn't work. Neither calling the function directly, neither changing from single to double quote. The only way I got to show a part of the where clause in the right location was to replace echo in my function for a return, but I can't have multiple returns in there (the function will end execution and part of the clause will be missing). Any ideas?

It's happening because you're echoing stuff instead of returning it...

function checkStatuses() {
    global $status;
    $return = "";
    $return .= " tl.task_log_status in (";
    foreach ($status as $option) {
        $return .= "'$option', ";
    }
    $return .= "'60') AND";
    return $return;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM