samedi 25 juin 2016

MySQL statement works in workbench but errors in PHP


The following sql code runs just fine in MySQL Workbench but returns

"string(228) "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SELECT p2.this_year,year(p.PAID_DATE) as current_year,c1.s1,c2.p1,c3.p2,ly.last_' at line 6" in PHP.

I've searched for an answer to no avail. Wondering if anyone has any ideas. Thanks in advance.

$dbinfo = dbinfo();
$con = mysqli_connect($dbinfo['localhost'],$dbinfo['localuser'],$dbinfo['localpass'],$dbase);
if (!$con) die('Could not connect: ' . mysqli_error($con));

$sql = "
SET @startdate = DATE(CURDATE()- INTERVAL DAYOFYEAR(CURDATE())+1 DAY), @enddate = CURDATE(),
    @laststart = DATE_SUB(@startdate, INTERVAL 1 YEAR),
    @lastend = DATE_SUB(@enddate, INTERVAL 1 YEAR)
    ;

SELECT p2.this_year,year(p.PAID_DATE) as current_year,c1.s1,c2.p1,c3.p2,ly.last_year,
    lyc1.s1,lyc2.p1,lyc3.p2
FROM btb.payments as p

join (
    select CLIENTID,sum(TOTAL) this_year,PAID_DATE
    from btb.payments
    where PAID_DATE between @startdate and @enddate
) as p2

join (
    select id_no,count(SUMMER_PT1) S1 
    from btb.Client
    where SUMMER_PT1 <> ''
) as c1
    on c1.ID_NO = p.CLIENTID

join (
    select id_no,count(PART1) P1
    from btb.Client
    where PART1 <> ''
) as c2

join (
    select id_no,count(PART2) P2
    from btb.Client
    where PART2 <> ''
) as c3

join (
    SELECT CLIENTID,sum(TOTAL) as last_year
    FROM btb.payments
    where PAID_DATE between @laststart and @lastend
) as ly

join (
SELECT d.CLIENTID,d.SESSION,count(p.CLIENTID) s1
FROM btb.Details d
join btb.payments p
    on p.CLIENTID = d.CLIENTID
where p.PAID_DATE between @laststart and @lastend
    and d.year = year(@laststart)
    and d.SESSION = 'S1'
) as lyc1
    -- on c1.ID_NO = p.CLIENTID

join (
SELECT d.CLIENTID,d.SESSION,count(p.CLIENTID) p1
FROM btb.Details d
join btb.payments p
    on p.CLIENTID = d.CLIENTID
where p.PAID_DATE between @laststart and @lastend
    and d.year = year(@laststart)
    and d.SESSION = 'P1'
) as lyc2

join (
SELECT d.CLIENTID,d.SESSION,count(p.CLIENTID) p2
FROM btb.Details d
join btb.payments p
    on p.CLIENTID = d.CLIENTID
where p.PAID_DATE between @laststart and @lastend
    and d.year = year(@laststart)
    and d.SESSION = 'P2'
) as lyc3

where p.PAID_DATE between @startdate and @enddate
;";

$result = mysqli_query($con, $sql);
if($result === false) {
    var_dump(mysqli_error($con));
}
else {
    print_r(mysqli_num_rows($result));
}

Aucun commentaire:

Enregistrer un commentaire