Add record for each array elements if missing in table



PHP Snippet 1:

$reference = $mysqli->query("create temporary table reference (periodid int(3), period varchar(15), playerid int, score int); ");

foreach ($playerids as $kp=>$pl) {
        foreach ($periods as $kd=>$pd) {
        $referenceins = $mysqli->query("insert into reference (periodid, period, playerid) values ('$kd', '$pd', '$pl')");
        }
    }

PHP Snippet 2:

foreach ($playerids as $kp=>$pl) {
    $reference2 = $mysqli->query("select periodid, period, playerid, date_time, @prev := IF(score > 0,score,@prev) AS score
                                from (select ref.periodid as periodid, ref.period as period, ref.playerid as playerid,
                                coalesce(tb.date_time, 'not found') as date_time,
                                coalesce(tb.score, 'not found') as score
                                FROM reference as ref 
                                LEFT JOIN table as tb
                                ON ref.period = tb.period AND ref.playerid = tb.playerid
                                WHERE ref.playerid = $pl
                                ORDER BY playerid asc, periodid asc) temp, (SELECT @prev := null) ini_value
                                ");
}