Is htmlspecialchars() Necessary Here ?

Hello,

One of the following code got htmlspecialchars. Which code is correct out of the two ?
Both codes build pagination section. Need to add security so users cannot sql inject.
Not using http_build_query function here as I want to build a pagination section without it and already built one with http_build_query function. Just learning different ways to build pagination section. Old way. New way. Ok ?

Page Format 1: https://localhost/Work/buzz/Templates/Pagination_TEMPLATE.php?tbl=links&bool=null&col_1=domain&input_1=brute.com&lmt=1&pg=1

Page Format 2: https://localhost/Work/buzz/Templates/Pagination_TEMPLATE.php?tbl=links&bool=null&col_1=domain&col_2=email_domain&input_1=brute.com&input_2=brute.com&lmt=1&pg=1

$i = 0;
while($i<$total_pages)
{
    $i++;
    if($bool=='and' || $bool=='or')
    {
        $serps_url = $_SERVER['PHP_SELF'].'?'.'tbl='.urlencode($tbl).'&'.'col_1='.urlencode($col_1).'&'.'col_2='.urlencode($col_2).'&'.'bool='.$bool.'&'.'input_1='.urlencode($input_1).'&'.'input_2='.urlencode($input_2).'&'.'lmt='.intval($limit).'&'.'pg='.intval($i);
    }
    else
    {
        $serps_url = $_SERVER['PHP_SELF'].'?'.'tbl='.urlencode($tbl).'&'.'col_1='.urlencode($col_1).'&'.'bool='.urlencode($bool).'&'.'input_1='.urlencode($input_1).'&'.'lmt='.intval($limit).'&'.'pg='.intval($i);
    }
    if($i==$page)
    {
        echo "<a href=\"$serps_url\"><b>$i</b></a>";
    }
    else
    {
        echo "<a href=\"$serps_url\">$i</a>";
    }
}

Thank you.

 $i = 0;
    while($i<$total_pages)
    {
        $i++;
        if($bool=='and' || $bool=='or')
        {
            $serps_url = $_SERVER['PHP_SELF'].'?'.'tbl='.urlencode($tbl).'&'.'col_1='.urlencode($col_1).'&'.'col_2='.urlencode($col_2).'&'.'bool='.$bool.'&'.'input_1='.urlencode($input_1).'&'.'input_2='.urlencode($input_2).'&'.'lmt='.intval($limit).'&'.'pg='.intval($i);
        }
        else
        {
            $serps_url = $_SERVER['PHP_SELF'].'?'.'tbl='.urlencode($tbl).'&'.'col_1='.urlencode($col_1).'&'.'bool='.urlencode($bool).'&'.'input_1='.urlencode($input_1).'&'.'lmt='.intval($limit).'&'.'pg='.intval($i);
        }
        if($i==$page)
        {
            echo '<a href="' .htmlspecialchars($serps_url) .'">' ."<b>$i</b>" .'</a>';
        }
        else
        {
            echo '<a href="' .htmlspecialchars($serps_url) .'">' ."$i" .'</a>';
        }
    }