Suppose, I have a table of events and I want to get all the events of some day (eg 2018-01-02)
| e1 | d1 | e2 | d2 | e3 | d3 |
----------------------------------------------------------------------
| event A | 2018-01-01 | event B | 2018-01-02 | event C | 2018-01-02 |
| event D | 2018-01-01 | NULL | NULL | NULL | NULL |
| NULL | NULL | event E | 2018-01-02 | event F | 2018-01-03 |
The problem is when I try to fetch results like this:
"SELECT * FROM table WHERE d1='2018-01-02' OR d2='2018-01-02' OR d3='2018-01-02' "
I'm given the whole row of results (in this case - all three rows). But I would like to get the separate results array with event and date. Like this:
Array
(
[0] => Array
(
event => event B
date => 2018-01-02
)
[1] => Array
(
event => event C
date => 2018-01-02
)
)
As for now, I did it this ugly way, executing 3 queries and joining their results:
$Sql=$conn->prepare("SELECT e1 AS event, d1 AS date FROM table WHERE d1='2018-01-02'");
$Sql->execute();
$Arr1 = $Sql->fetchAll(PDO::FETCH_ASSOC);
$Sql=$conn->prepare("SELECT e2 AS event, d2 AS date FROM table WHERE d2='2018-01-02'");
$Sql->execute();
$Arr2 = $Sql->fetchAll(PDO::FETCH_ASSOC);
$Sql=$conn->prepare("SELECT e3 AS event, d3 AS date FROM table WHERE d3='2018-01-02'");
$Sql->execute();
$Arr3 = $Sql->fetchAll(PDO::FETCH_ASSOC);
$Arr=array();
foreach($Arr1 AS $a){
$Arr[]=array($a['event'],$a['date']);
}
foreach($Arr2 AS $a){
$Arr[]=array($a['event'],$a['date']);
}
foreach($Arr3 AS $a){
$Arr[]=array($a['event'],$a['date']);
}
print_r($Arr);
But I'm sure there should be some more adequate way to do this. Either by modifying SQL or PHP. Thanks in advance.
have look at https://dev.mysql.com/doc/refman/5.7/en/union.html try something like this
$Sql=$conn->prepare("(SELECT e1 AS event, d1 AS date FROM table WHERE d1='2018-01-02') UNION (SELECT e2 AS event, d2 AS date FROM table WHERE d2='2018-01-02') UNION (SELECT e3 AS event, d3 AS date FROM table WHERE d3='2018-01-02') ");
$Sql->execute();
$Arr = $Sql->fetchAll(PDO::FETCH_ASSOC);
alse note that date is a reserved word so you might have to write it with back ticks... not sure though because I simply don't use them ;)
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.