$sql = "SET @daynum = 0, @weeknum = 1;
        SELECT
            a.week,
            a.day,
            a.date,
            a.userid,
            a.name,
            COALESCE ( b.starttime, a.start ) AS start,
            COALESCE ( b.finishtime, a.finish ) AS finish
        FROM
            (
            SELECT
                template.week,
                template.day,
                template.date,
                rotatemplate.userid,
                userdetails.name,
                rotatemplate.start,
                rotatemplate.finish,
                userdetails.rotaorder 
            FROM
                (
        WITH RECURSIVE daterange AS (
            SELECT
                '".date( "Y-m-d", $firstmonday )."' AS date UNION
            SELECT
                DATE_ADD( daterange.date, INTERVAL 1 DAY ) 
            FROM
                daterange 
            WHERE
                DATE_ADD( daterange.date, INTERVAL 1 DAY ) <= '".date( "Y-m-d", $lastsunday )."' )
                SELECT 
                IF ( @daynum < 7, @daynum := @daynum + 1, @daynum := 1) AS 'day',
                IF ( @daynum = 1, @weeknum := @weeknum + 1, @weeknum) - 1 AS 'week',
                daterange.date as date
        FROM
            daterange) template
                LEFT JOIN rotatemplate ON template.week = rotatemplate.week 
                AND template.day = rotatemplate.day
                LEFT JOIN userdetails ON rotatemplate.userid = userdetails.userid 
            ) a
            LEFT JOIN rotavariations b ON a.userid = b.userid 
            AND a.date = b.date 
        ORDER BY
            a.week,
            a.day,
            a.rotaorder";
$result = mysqli_query( $internalconnection, $sql );
(I know that this is prone to SQL injection etc, but humour me please!)
This produces an error due to passing the user defined variables on the first line (it works fine running it directly in mysql rather than passing it from PHP
I believe that I can get around this using mysqli_multi_query, which then avoids the error, however I can't understand how to iterate the results.
Please could you assist using procedural style rather than Object Orientated.
