cute
cute

Reputation: 691

search multi keywords from sql

So I'm getting data from sql like this :

$date = 1-02-2011
$sql = "SELECT * FROM abc  WHERE date='$date'"

Now I want to get data from multiple dates for creating a graph

$date1 = 1-02-2011
$date2 = 2-02-2011
$date3 = 3-02-2011
$date4 = 4-02-2011
$date5 = 5-02-2011
$date6 = 6-02-2011

and so on..

Is there any quick way? Or will have to create different querys for each date?

Upvotes: 1

Views: 190

Answers (1)

Mark Byers
Mark Byers

Reputation: 838116

You can use IN:

SELECT * FROM abc WHERE date IN ('2011-02-01', '2011-02-03', '2011-02-05')

or if your dates are always consecutive like in your example then you could use BETWEEN:

SELECT * FROM abc WHERE date BETWEEN '2011-02-01' AND '2011-02-06'

Then to read the results:

$result = mysql_query($query) or trigger_error(mysql_error());

while ($row = mysql_fetch_assoc($result)) {
    $date =  $row['date'];
    $col1 = $row['col1'];
    // Do something with the results.
}

Edit: To show NULL for missing values you can use a LEFT JOIN:

SELECT T1.date, T2.*
FROM (
    SELECT '2011-02-01' AS date
    UNION ALL
    SELECT '2011-02-02'
    UNION ALL
    ...
    UNION ALL
    SELECT '2011-02-06'
) AS T1
LEFT JOIN T2
ON T1.date = T2.date

Upvotes: 2

Related Questions