Too many errors with PHP code

This is a lazy lame excuse but as a PHP noob, I’m seeing if any ‘experts’ can look at the following code and clean it for me. I’ve run into problems as a kind help on this site directed me to go another way about my project and I think its near enough working except for some syntax errors -

The code:


<?php include('connect.php')?>
<?php
function get_search_params()
{
    $params = array();

    foreach(array('services', 'area') as $param)
    {
        if( ! empty($_GET[ $param ]))
        {
            $params[ $param ] = $_GET[ $param ];
        }
    }

    return $params;
}

if($params = get_search_params())
{
    $sql = 'SELECT * FROM family_support WHERE 1 = 1';

    if(isset($params['services']))
    {
        $sql .= sprintf(" AND services = '%s'", $params['services']);
    }
		
	if(isset($params['area']))
    {
        $sql .= sprintf(" AND area = '%s'", $params['area']);
    }

    if(isset($params['org_name']))
    {
        $sql .= sprintf(" AND org_name LIKE '%%%s%%'", $params['org_name']);
    }

    $sql .= ';';
}
?>
<!DOCTYPE>
<html>
<head>
<title>Search</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link rel="shortcut icon" href="images/ofc_fav.ico" />
<link rel="stylesheet" type="text/css" media="screen" href="stylesheets/main.css"/>
<link rel="stylesheet" type="text/css" media="screen" href="stylesheets/jquery-ui-1.8.17.custom.css"/>
<link rel="stylesheet" type="text/css" media="print" href="stylesheets/print.css"/>
<link rel="stylesheet" type="text/css" media="handheld, only screen and (max-width: 480px), only screen and (max-device-width: 480px)" href="stylesheets/mobile.css"/>
    <!--[if lte IE 8]> <link rel="stylesheet" type="text/css" href="stylesheets/ie.css"/> <![endif]-->
<script type="text/javascript" src="jquery-ui-1.8.17.custom.min" ></script>
<script type="text/javascript">
$(document).ready(function() {
	//Default Action
	$(".tab_content").hide();
	$("ul.tabs li:first").addClass("active").show();
	$(".tab_content:first").show();

	//On Click Event
	$("ul.tabs li").click(function() {
		$("ul.tabs li").removeClass("active");
		$(this).addClass("active");
		$(".tab_content").hide();
		var activeTab = $(this).find("a").attr("href");
		$(activeTab).fadeIn();
		if(activeTab == '#tab2') {
			$(window).resize(function(){
			//$("#tab2").css({'display':'block'});
			//$("#map_canvas").css({'width':'630px', 'height':'400px'});
			//initialize();
			//alert('Changed!');
			});
    		}
		return false;
	});
});
</script>

<style type="text/css" media="screen">
/* Google map */
#map_canvas {width: 100%; height: 500px;border:1px solid #dbdbdb;}
/*paginate style */

fs. img.logo
{
position:absolute;
left:100px;
top:150px;
}
</style>
</head>
<body>
        <form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="get">
        <div>
            <label for="services" >Support Service:</label>
        	<select name="services[]" id="services" multiple>
            <option value="All">All</option>
            <option value="carer">Carer</option>
            <option value="childminder">Childminder</option>
            <option value="children_socialcare">Children Social Care</option>
            <option value="creche">Creche</option>
            <option value="day_nursery">Day Nursery</option>
            <option value="disability">Disability</option>
            <option value="domestic_sexualabuse">Domestic / Sexual Abuse</option>
            <option value="drug_alcoholmisuse">Drug / Alcohol Misuse</option>
            <option value="education_fs">Education</option>
			<option value="employment_training">Employment / Training</option>
            <option value="familysupport">Family Support</option>
			<option value="healthservice">Health Service</option>
			<option value="housing_fs">Housing</option>
			<option value="leisure_youthservice">Leisure / Youth Service</option>
			<option value="lifestart">Lifestart</option>
			<option value="mentalhealth">Mental Health</option>
			<option value="minority_ehtnic Support">Minority Ehtnic Support</option>
            <option value="outofschool">Out of School</option>
			<option value="parent_toddler">Parent & Toddler</option>
			<option value="playgroup">Playgroup</option>
			<option value="signposting_advice">Signposting / Advice</option>
			<option value="summer_scheme">Summer Scheme</option>
			<option value="youth_offending">Youth Offending</option>
            </select>
        </div>
        <div>
		<label for="area" accesskey="a"> Area:</label>
        <select name="area" id="area">
            <option value="All">All Counties</option>
            <optgroup label="Co. Cavan">
                <option value="All Cavan">All Cavan</option>
                <option value="Bailieborough">Bailieborough</option>
                <option value="Ballyjamesduff">Ballyjamesduff</option>	
                <option value="Belturbet">Belturbet</option>	
                <option value="Cavan">Cavan</option>
                <option value="Cootehill">Cootehill</option>	
                <option value="Kingscourt">Kingscourt</option>	
                <option value="Virginia">Virginia</option>
            </optgroup>
            <optgroup label="Co. Donegal">
                <option value="All Donegal">All Donegal</option>
                <option value="Ballybofey">Ballybofey</option>	
                <option value="Ballyshannon">Ballyshannon</option>
                <option value="Bunbeg-Derrybeg">Bunbeg-Derrybeg</option>
                <option value="Buncrana">Buncrana</option>	
                <option value="Bundoran">Bundoran</option>	
                <option value="Carndonagh">Carndonagh</option>
                <option value="Castlefin">Castlefin</option>
                <option value="Convoy">Convoy</option>
                <option value="Creeslough">Creeslough</option>
                <option value="Donegal">Donegal</option>
                <option value="Dunfanaghy">Dunfanaghy</option>
                <option value="Dungloe">Dungloe</option>
                <option value="Glenties">Glenties</option>
                <option value="Killybegs">Killybegs</option>	
                <option value="Letterkenny">Letterkenny</option>
                <option value="Lifford">Lifford</option>
                <option value="Milford">Milford</option>
                <option value="Moville">Moville</option>
                <option value="Muff">Muff</option>
                <option value="Newtowncunningham">Newtowncunningham</option>
                <option value="Ramelton">Ramelton</option>
                <option value="Raphoe">Raphoe</option>
            </optgroup>
            <optgroup label="Co. Leitrim">
                <option value="All Leitrim">All Leitrim</option>
                <option value="Manorhamilton">Manorhamilton</option>
                <option value="Carrick-on-Shannon">Carrick-on-Shannon</option>
            </optgroup>
            <optgroup label="Co.Louth">
                <option value="All Louth">All Louth</option>
                <option value="Ardee">Ardee</option>
                <option value="Clogherhead">Clogherhead</option>
                <option value="Drogheda">Drogheda</option>	
                <option value="Dundalk">Dundalk</option>	
                <option value="Dunleer">Dunleer</option>	
                <option value="Tullyallen">Tullyallen</option>	
            </optgroup>
            <optgroup label="Co.Meath">
                <option value="All Meath">All Meath</option>
                <option value="Ashbourne">Ashbourne</option>
                <option value="Athboy">Athboy</option>
                <option value="Ballivor">Ballivor</option>
                <option value="Ceannanus Mór (Kells)">Ceannanus Mór (Kells)</option>
                <option value="Clonee Village">Clonee Village</option>	
                <option value="Duleek">Duleek</option>	
                <option value="Dunboyne">Dunboyne</option>	
                <option value="Dunshaughlin">Dunshaughlin</option>	
                <option value="Enfield">Enfield</option>	
                <option value="Laytown-Bettystown-Mornington">Laytown-Bettystown-Mornington</option>	
                <option value="Navan (An Uaimh)">Navan (An Uaimh)</option>	
                <option value="Oldcastle">Oldcastle</option>	
                <option value="Ratoath">Ratoath</option>	
                <option value="Slane">Slane</option>	
                <option value="Stamullen">Stamullen</option>	
                <option value="Trim">Trim</option>
            </optgroup>
            <optgroup label="Co.Monaghan">
                <option value="All Monaghan">All Monaghan</option>
                <option value="Ballybay">Ballybay</option>	
                <option value="Carrickmacross">Carrickmacross</option>	
                <option value="Castleblayney">Castleblayney</option>	
                <option value="Clones">Clones</option>	
                <option value="Monaghan">Monaghan</option>
            </optgroup>
            <optgroup label="Co. Sligo">
                <option value="All Silgo">All Silgo</option>
                <option value="Ballymote">Ballymote</option>
                <option value="Sligo">Sligo</option>	
                <option value="Strandhill">Strandhill</option>	
                <option value="Tubbercurry">Tubbercurry</option>
            </optgroup>
        </select>
            </div>
            <div>
                <label for="org_name">Keyword</label>
                <input id="org_name" type="text" name="org_name" />
            </div>
            <div>
                <input type="submit" value="Search" />
            </div>
        </form>

<!--Main Content-->
<div style="width:100%">

<div class="container">

    <ul class="tabs">
    <li><a href="#tab1">Details</a></li>
    <li><a href="#tab2" id="showMap">Map</a></li>
    <li><a href="#tab3">Feedback</a></li>
    </ul>

<!-- Start tab container -->
<div class="tab_container">

    <div id="tab1" class="tab_content">

        <!--Pagination-->
<div style="float:right"><p>ADD PAGINATE HERE</p></div>


<!--SQL QUERY HERE-->

<?php
$svcs = $_POST["services"];  // gets a PHP array, thanks to the [] in name of <select>

$where = "";
$delim = "";
foreach ( $svcs as $service ) // so we check each name in the array of services
{
    if ( $service == "All" ) // special handling if All is selected:
    {
        $where = ""; // we want record no matter what service, so ignore other services
        break; // out of the for loop
    }
    $where .= $delim . $service . "=1"; // add a check for current service
    $delim = " OR ";
}
if ( $where != "" ) $where = " (" . $where . ") ";  // if any selected, put parens around them

// then process the "area" select:
$area = $_POST["area"];
if ( $area != "" && $area != "All" )
{
    $where .= " AND area = '" . $area . "' ";
}

 and the org_name
$org = $_POST["org_name"];
if ( $org != "" )
{
    $where .= " AND org_name = '" . $org . "' ";
}
$sql = "SELECT * FROM family_support';
if ( $where != '') { $sql .= " WHERE " . $where };

//maybe tack on an ORDER BY clause and then execute the query


//echo result and order by name
$sql .=" ORDER BY org_name";

//echo $sql_result;
$result =  mysql_query($sql, $dbh) or die ('Database currently being updated, please try again later!');
$num=mysql_numrows($result);



// first, debug the query:
echo "<hr/>DEBUG SQL: " . $sql . "<hr/>\
";


?>

<div id="details-tab">
<div class="search-container">
<ul class="searchresults">

<?php
//quries used on results table;
    $i=0;
    while ($i < $num) {
    $idnumber = mysql_result($result, $i,'id');
    $org_name     = mysql_result($result, $i, 'org_name');
    $org_address  = mysql_result($result, $i, 'org_address');
    $tel = mysql_result($result, $i, 'tel');
    $email = mysql_result($result, $i, 'email');
    $website = mysql_result($result, $i, 'website');
    //$org_type = mysql_result($result, $i, 'org_type');
    $image_path = mysql_result($result, $i, 'image_path');
    //lat and long for map co-ordinates
    $lat = mysql_result($result, $i, 'lat');
    $long = mysql_result($result, $i, 'long');

//search feedback finshed----------------->


echo'
<li>
    <h3 class="fs"> '.(empty($idnumber) ? '&nbsp;' :' <a  href="familysupport-profile.php?id='.$idnumber.'">'.$org_name.'</a>').'</h3>
        <p class="fs">  p: '.(empty($tel) ? '&nbsp;' : $tel).'<br/>';
//only show email if available
                if($email!== "")
                        {
                        echo 'e: <a class="bluelink" href="mailto: '.(empty($email) ? '&nbsp;' : htmlspecialchars($email)).'?Subject=Enquiry%20from%20family%20support%20search%20www.outcomesforchildren.org/familysupport">'.(empty($email) ? '&nbsp;' : htmlspecialchars($email)).'</a><br/>';
                        }
//only show website if available
                if($website!== "")
                        {
                        echo 'w: <a class="bluelink" target="_blank" href="'.$website.'">'.$website.'</a>';
                        }?>
</p>
<?php
//only show logo if available
                if($image_path!== "")
                        {
                        echo '<a href="'.(empty($website) ? '&nbsp;' : $website).'" target="_blank"><img class="agent-logo" src="'.$image_path.'" alt="'.$org_name.'" title="'.$org_name.'"/><a/>';
                        }
                        ?>
</li>

<?php '
   ';
$i++;
}
echo '
    ?>

</ul>
</div>
</div>';

<?php
}
else
{
echo '<h2><a class="bluelink" href="form.html">Sorry but no results were found, try searching again?</a></h2>';

// Offer a google or bing search as an alternative
echo "<p><a href=\\"http://www.google.com/search?q=" . $sql_result . "\\" target=\\"_blank\\" class=\\"bluelink\\" title=\\"Look up " . $sql_result . " on Google\\">Click here</a> to try the search on google</p><br/>";
}
 ?>
</div>
    <!--END OF TAB 1 RESULTS-->

<div id="tab2" class="tab_content">
<h3 class="fs" id="map">Location Map</h3>

    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&region=GB"></script>
    <script type="text/javascript">
    //<![CDATA[
    var customIcons = {
      service: {
        icon: 'images/daycare-marker.png',
        shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
      },
    };


	    $(document).ready(function() {

	//Default Action
	    $(".tab_content").hide();
	    $("ul.tabs li:first").addClass("active").show();
	    $(".tab_content:first").show();

	//On Click Event
	    $("ul.tabs li").click(function() {
		$("ul.tabs li").removeClass("active");
		$(this).addClass("active");
		$(".tab_content").hide();
		var activeTab = $(this).find("a").attr("href");
		$(activeTab).fadeIn();
		if(activeTab == '#tab2') {
		$(window).resize(function(){
			//$("#tab2").css({'display':'block'});
			//$("#map_canvas").css({'width':'630px', 'height':'400px'});
			//initialize();
			//alert('Changed!');
		});
    	}
		return false;
});

        var map = new google.maps.Map(document.getElementById("map_canvas"), {
        center: new google.maps.LatLng(54.159218,-7.514648), // CHANGE THIS AUTO CENTRE
        zoom: 8, // CHANGE TO AUTO ZOOM
        mapTypeId: 'roadmap',
        mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}
});


      var infoWindow = new google.maps.InfoWindow;

      // Change this depending on the name of your PHP file
      downloadUrl("phpsqlajax_genxml3.php", function(data) {
        var xml = data.responseXML;
        var markers = xml.documentElement.getElementsByTagName("marker");
        for (var i = 0; i < markers.length; i++) {
          var bounds = new google.maps.LatLngBounds(); //auto zoom?
          var name = markers[i].getAttribute("name");
          var address = markers[i].getAttribute("address");
          var type = markers[i].getAttribute("type");
          var point = new google.maps.LatLng(
              parseFloat(markers[i].getAttribute("lat")),
              parseFloat(markers[i].getAttribute("lng")));
          var html = "<b>" + name + "</b> <br/>" + address;
          var icon = customIcons[type] || {};
          var marker = new google.maps.Marker({
            map: map,
            position: point,
            icon: icon.icon,
            shadow: icon.shadow
          });
          bounds.extend(point);
          map.fitBounds(bounds);
            var listener = google.maps.event.addListener(map, "idle", function() {
            if (map.getZoom() > 12) map.setZoom(9);
            google.maps.event.removeListener(listener);
          });

          bindInfoWindow(marker, map, infoWindow, html);
        }
      });

    function bindInfoWindow(marker, map, infoWindow, html) {
      google.maps.event.addListener(marker, 'click', function() {
        infoWindow.setContent(html);
        infoWindow.open(map, marker);
      });
    }

    function downloadUrl(url, callback) {
      var request = window.ActiveXObject ?
          new ActiveXObject('Microsoft.XMLHTTP') :
          new XMLHttpRequest;

      request.onreadystatechange = function() {
        if (request.readyState == 4) {
          request.onreadystatechange = doNothing;
          callback(request, request.status);
        }
      };

      request.open('GET', url, true);
      request.send(null);
      }
        function doNothing() {}
    	// Function added to help reset map and container boundaries - THIS HAS TO STAY FOR THE TABS TO DISPLAY THE MAP!
        $("#showMap").click(function() {
        $("#tab2").css({'display':'block'});
        $("#map_canvas").css({'width':'630px', 'height':'400px'});
        //alert('showMap Clicked!');
		google.maps.event.trigger(map,'resize');
        });
    });
    //]]>

    </script>

    </script>
    <div id="map_canvas"></div>
    <h3>Map not showing the correct location?</h3>

    </div>
<?php
mysql_close($dbh);
?>
<!-- Tab 3 for Feedback form-->
<div id="tab3" class="tab_content">
<h3 class="fs" id="feedback">Feedback</h3>
    <div id="contact-area">
		        <br />
				<form id="contact-area" method="post" action="send-mail.php">
				<label for="name">Name*:</label>
				<input type="text" name="name" />
	
				<label for="email">Email*:</label>
				<input type="text" name="email" />

				<label for="subject">Subject:</label>
				<input type="text" name="subject" />
				
				<label for="message">Message:</label><br />
				<textarea name="message" rows="20" cols="20"></textarea>

                <input type="reset" name="clear" value="Clear" class="reset-button" />
				<input type="submit" name="submit" value="submit" class="submit-button" />

                <p class='hide' id='response'></p>
			<div class='hide'>
				<label for='spamCheck'>Do not fill out this field</label>
				<input name='spam_check' type='text' value='' />
			</div>
			</form>
		<div style="clear: both"></div>
	</div>

</div>
    <!--END OF FEEDBACK TAB-->
</div>
    <!--End of Tab Container-->
<div style="clear: both"></div>
    <h3>Hello there some bottom content if needed!</h3>
    </div>
</div>
</div>
</div>
<!--Main Content End-->
</td>
</tr>
</table>
    <!--Footer-->
</body>
</html>

i'm basically trying to develop a search directory...



Try splitting your page into sections and gradually include a section, eliminate errors then include the next section.



<?php
  error_reporting(-1);
  ini_set('display_errors',1);

 if(0) include('connect.php');

 if(0) include('search_parameter_stuff.php');

 if(0) include('html_page_stuff.php');
 if(0) include('next_section.php');
 if(0) include('next_section.php');
 if(0) include('next_section.php');

  echo 'Happiness is having no errors or warnings';

Thanks John this could help.

post the error messages you are getting.

To debug it yourself you can use echo statements followed by die(); to check values of variables and your code logic.

kennard could you provide an example of how to do this,

For example with this line


$sql = "SELECT * FROM family_support';
if ( $where != '') { $sql .= " WHERE " . $where }; 

how would I add

die()

?

The first error I’m getting is;

Parse error: syntax error, unexpected T_ELSE in D:\www\ofcftp\familysupport.php on line 360

@Stephen_


<?php
  error_reporting(-1);
  ini_set('display_errors', 1);

  if(1) { include 'connect.php';      }
  if(1) { include '__functions.php';  }
  if(1) { include '__html_first.php'; }
  if(1) { include '__sql_001.php';   }  /* REMOVED ERRORS */
  if(1) { include '__html_first.php'; }
  if(1) { include '__sql_002.php';   }
  if(1) { include '__html_003.php'; }

  echo '<br />';
  echo __FILE__;
  echo '<br />';
  echo "i'm basically trying to develop a search directory...";


.
.
.

‘__sql_001.php’; /* REMOVED ERRORS */



<?php
$svcs = $_POST["services"];  // gets a PHP array, thanks to the [] in name of <select>

$where = "";
$delim = "";
foreach ( $svcs as $service ) // so we check each name in the array of services
{
    if ( $service == "All" ) // special handling if All is selected:
    {
        $where = ""; // we want record no matter what service, so ignore other services
        break; // out of the for loop
    }
    $where .= $delim . $service . "=1"; // add a check for current service
    $delim = " OR ";
}
if ( $where != "" ) $where = " (" . $where . ") ";  // if any selected, put parens around them

// then process the "area" select:
$area = $_POST["area"];
if ( $area != "" && $area != "All" )
{
    $where .= " AND area = '" . $area . "' ";
}

# Parse error: syntax error, unexpected T_LOGICAL_AND in __sql_001.php on line 25
# John_Betong added #
# and the org_name


$org = $_POST["org_name"];
if ( $org != "" )
{
    $where .= " AND org_name = '" . $org . "' ";
}
# Parse error: syntax error, unexpected T_STRING in __sql_001.php on line 39
# John_Betong replaced ' with "
# $sql = "SELECT * FROM family_support';
$sql = "SELECT * FROM family_support";

# Parse error: syntax error, unexpected '}' in __sql_001.php on line 40
# John_Betong replaced  };  with  ;}
# if ( $where != '') { $sql .= " WHERE " . $where };
if ( $where != '') { $sql .= " WHERE " . $where; }

//maybe tack on an ORDER BY clause and then execute the query


//echo result and order by name
$sql .=" ORDER BY org_name";

//echo $sql_result;
$result =  mysql_query($sql, $dbh) or die ('Database currently being updated, please try again later!');
$num=mysql_numrows($result);



// first, debug the query:
echo "<hr/>DEBUG SQL: " . $sql . "<hr/>\
";

# Not required - see manual ?>


That error message usually means you have mismatched () or {} somewhere.

die() function stops execution of the php script when the call to die() is made. You can put it anywhere in your script.

For example:


$myVar = 'someValue';  //normal code

echo $myVar ;  //for debugging to output the current value of $myvar
die();              // terminates the running of the php script

Thanks for the help on this - found a few more errors now, hopefully will get there!