String variable echos desired value but retains the ‘script’ that created it when I try to assign it to another string

Trying to pass a parameter ‘name’ to B.PHP based upon a link that was clicked on in A.PHP

This parameter will then be used to create the value for a ‘Where colum_name = value’ part of an SQL Query used in B.PHP

$sql = “Select stuff where Name = ” … append name parameter … “order by stuff”;

I use the following script in B.PHP to assign the ‘name’ passed to a parameter called ‘horse’. This works fine…

<script>
function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[[]]/g, '\$&');
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';

 alert(decodeURIComponent(results[2].replace(/+/g, ' ')));  
    return decodeURIComponent(results[2].replace(/+/g, ' '));
}

 var horse = getParameterByName('horse')

 document.getElementById("horse").innerHTML = horse;

</script>

I then use the following code using an output buffer to build the sql query…

ob_start();

  echo  "SELECT rh.Race_Id, rh.RH_Position, r.Race_Date, r.Race_Course, r.Race_Title, 
        r.Race_Going, r.Race_Distance, r.Race_Value from racetable r
        join race_horse_table rh on r.Race_Id = rh.Race_Id
        join horsetable h on rh.Horse_Id = h.Horse_Id
        where h.Horse_Name = '" ;                    //Echo first part of query
  echo  "<script>document.write(horse)</script>";    //Get the name of the horse
  echo  "' order by Race_Date DESC;" ;               //Complete the query

  $sql  = ob_get_contents();  
  ob_get_clean();

When I echo this string it is exactly what I want it to be, but when I submit it to SQL
it receives the text “document.write(horse)” instead of the horse’s name