user3061975
user3061975

Reputation:

MySQL - Using array within the select

What is the correct way to do what I'm trying? Discover that the checks IN does what I need.

$hierarquia = implode(",", $_POST['hierarquia']);
// Show: 3,4

(
    SELECT planoDeConta FROM `financ_receita` 
    WHERE data BETWEEN '2011-01-01' AND '2013-12-30'
    planoDeConta IN ($hierarquia)

) UNION ALL (

    SELECT planoDeConta FROM `financ_despesa` 
    WHERE data BETWEEN '2011-01-01' AND '2013-12-30'
    planoDeConta IN ($hierarquia)

)

Upvotes: 0

Views: 103

Answers (2)

user3061975
user3061975

Reputation:

The values ​​must be quoted. To do this, simply use the code below:

$hierarquia2 = sprintf( "'%s'", implode( "','", $_POST['hierarquia'] ) );

Thank you all for your help.

Upvotes: 0

Gordon Linoff
Gordon Linoff

Reputation: 1270873

You have a syntax error because you are missing a conjunction before the second condition in each query:

(
    SELECT planoDeConta
    FROM `financ_receita` 
    WHERE data BETWEEN '2011-01-01' AND '2013-12-30' AND
          planoDeConta IN ($hierarquia)

) UNION ALL (
    SELECT planoDeConta
    FROM `financ_despesa` 
    WHERE data BETWEEN '2011-01-01' AND '2013-12-30' AND
          planoDeConta IN ($hierarquia)
)

This should work because you are doing the variable substitution for $hierarquia at the "query-string" level. It would not work if you just input the value as a string.

Upvotes: 1

Related Questions