Hello -

I'm new to PHP, only been learning it for about a month, but I think I am starting to get the hang of it. I am working on a project that involves the Google Maps API which uses markers that are populated by values from a MySQL database. I am esentially attempting to create a profile option for each marker location on the map.

The javascript code that populates the map markers is the following.

var html = '<b>' + name + '</b> <br/>' + address + '<br />' + '<a href=\"/locations/' + state + '/' + city + '/' + name + '\">View Profile</a>';

As you can see there is a link created using the values for state, city, and address.

My goal now is to use PHP to run through that database and actually create a file for each row in the database. So it has to create a file in the location "root/locations/state(value of $state)/city(value of $city)/name(value of $name)".

I have written a code that I think should do the job, however it is not creating the file in the location. I worked through all the errors, and now none are reported, so I am stumped as to why it will not work.

Here is my code:



$contents = 'Testing to see if this makes it onto the page'; 

include ('mysql_connect.php');
$query = "SELECT id, name, state, city, as sd FROM markers";
$result = @mysql_query($query);

if ($result) {
while ($row = mysql_fetch_assoc($result)) {

$mydir = $_SERVER['DOCUMENT_ROOT'].'/locations/';
if(!empty($row['state']) && !empty($row['city']) && !empty($row['name'])){
   $mydir .= $row['state'].'/'.$row['city'].'/';
   if(file_exists($mydir) && is_writable($mydir)){
      $mydir .= $row['name'].'.php';
      // put the rest of the code to write the file here

$handle = fopen($_SERVER['DOCUMENT_ROOT'].'/locations/'.$row['state'].'/'.$row['city'].'/'.$row['name'].'.php', 

"w") or die("Could Not Open File");  

$lock = flock($handle, LOCK_EX);  

if ($lock){ 
 fputs($handle, $contents);  
 flock($handle, LOCK_UN);  


If I remove all the SQL and database stuff, it does work, the code for that is:


$contents = 'Testing to see if this makes it onto the page';  

$handle = fopen(test.'.'.txt, "w");   

$lock = flock($handle, LOCK_EX);   

if ($lock){  
 fputs($handle, $contents);   
 flock($handle, LOCK_UN);   


Any help I can get is greatly apreciated. I have asked in a couple of other places yet no one can seem to figure out why the values in the database are not passed to the variables in my code.

Any links to guides or examples that acheive the same goal would alos work. I simply cant find any that use variables in their path anywhere.


Why do you have a file for every location? Couldn't you just send an id to a landing page that could get the data you need.

I think you might be over-complicating things. As I don't know the whole situation I can't be sure though.

Thankyou for the quick response, if there is a less complicated way I am all ears.

I will try to better explain my project.

On the site there is a Google Map that is populated with markers that get there values from a database. Each time a new location is added into the database through a form that takes the values "Name", "Address", "City", and "State". The address city and state determine the location of the marker on the map.

Inside of the little info bubble that pops up when those markers are clicked is the name and full address, then a "View Profile" link. The URL for that link is automatically generated using the state, city, and address values. This is what the first code in my last post did.

So basically each time a new location is added (this feature is open to public so there may be many) a new URL is automatically generated. Because of this, I need to automatically generate the file for that location, otherwise it is a broken link. I figured if I could go through each row, and create a file, it would work out.

Am I going about this the right way? Or am I completely on the wrong path?

If you would like to see an example of the map, my workspace for it is at http://www.davasso.com/clients/fcb/, just type "Everett" into the search bar and you will see the marker, and its URL path it takes. I also havnt made my layout compatible for every browser yet, so it may be offset.

There is an easier way. Instead of having a page for each location, use one page that will fill a profile template.

You could use profile.php?id=location_id where location_id is the id of the location in the database.

One page can do it all. Kind of the point of php. If you want paths like that you might want to look into mod_rewrite.

I recently created an app similar to this. The only difference is that you could type in a from and to address and it would find locations within 10 miles of the road the directions give you. Pretty cool I thought.

Go to Seagrease.com and register for an account. In the members area there is a "Find A Restaurant" link. Try that out. For a from use "Valley Center, KS" and to use "Hollywood, CA".

I think I understand what you are refering to, I know I have seen URL's with that syntax before. Could you by chance reccomend a good place to look for guides or examples that use that method. I'm still fairly new to PHP so I usually need to go step by step to understand a function completely.

I did check out Seagrease, and registered, but for some reason whenever I enter those two locations and hit enter, it returns me to the members welcome page.


do you have javascript enabled?

I am looking for some good resources for you.

Good call, it was the javascript.

And thanks a ton for taking the time to help point me in the right direction.

Here is one I found just using google: http://www.workingwith.me.uk/articles/scripting/mod_rewrite
Its seems like it should give you a good basis. There is apache documentation for it, but if your new to that stuff, you won't understand most of it.

Url rewriting uses regular expressions, which from my experience are not fun, but you learn to use them. A simple google search will do the trick.

Here is the rewrite site: http://www.webmaster-toolkit.com/mod_rewrite-rewriterule-generator.shtml

Do you understand what I am talking about with the location_id stuff? I can give you some examples if you need them.

Hey thanks kkeith29,

I will read them over and focus on them.

Examples for the the location_id stuff would be great. Ive been searching forums and using Google for the last couple hours trying to find examples but the most I could really find was http://www.codingforums.com/archive/index.php/t-107879.html and there was nothing there for me to go off of. Ive still got a ways to go in my learning before I fully understand how little snippets of code work without the rest of the code accompanying them.

I will make some examples shortly.

Also, I saw a potential problem which would cause you problems. You have an error in the query. Remove , as sd .

Do you have any code for the profile page. I mean like a layout you are wanting.

Thanks so much kkeith29.

Alright I will give it a try with the as sd removed. That was part of a script I made for a testimonials page at one point, and I was using that script as a starting to point when I got started on this project.

As for my template, I was planning on using my design I have for the rest of the website if that is possible. I know I would need to set areas that get their values from the variable. From what I have learned so far, I beleive I can set the design in a variable in another PHP file, and then include that file in my script for creating multiple pages, but I may be wrong. I'd probably have to find a guide that teaches how to parse the code as well I am guessing.

I do apologize for being a newb at this, maybe bit off more than I can chew this soon. I'm a new web design student and got hooked on coding right away, however my current professors at the UW here in Seattle dont know a thing about PHP, so I have been spending all my time teaching myself lately.

And again, I really am thankful for all the help.

Yes, you can use the design for it. This is pretty much what php was made for. PHP outputs html.

Yes, you can include files. One of the great features of php. Saves a lot of work. You can make a header and footer file that contain the basic layout and design, then include them on every page. If you need to make a change, then you change the header/footer file and the whole site is updated with it.

Example of the location_id:
In the javascript you would only need to put 'profile.php?id=' + id for the link the profile. Then on the profile page:


$host = 'localhost';
$user = 'username';
$pass = 'pa55w0rd';
$name = 'database_name';

$con = mysql_connect( $host,$user,$pass ) or die('Error: Unable to connect');
mysql_select_db( $name,$con ) or die('Error: Unable to select database');

if ( isset( $_GET['id'] ) ) { //checks to see if the id "is set" in the url
  //if id is found, then proceed.
  $id = mysql_real_escape_string( $_GET['id'] ); //sets the id in the url into the $id variable, also prevents sql injection hacks with the mysql_real_escape_string function
  $query = mysql_query( "SELECT `name`,`state`,`city` FROM `markers` WHERE `id` = {$id} LIMIT 1" ); //select data from database based on the id
  if ( mysql_num_rows( $query ) == 1 ) { //if there is a result found process it
    list( $name,$state,$city ) = mysql_fetch_row( $query ); //put the data from the database into variables
    $html =<<<HTML
<div>This is where you can put your design. Where you want the variables use just put {$name} for name, {$state} for state, and {$city} for city. Done.</div>
HTML; //there can be NO white space before HTML; on this line
    echo $html; //lastly send html to browser
else {
  //if the id is not set, then kill the page (or make a nice error)
  die('Error - ID not found!');


If you need anymore help, just ask.

So I think I understand how this works now, but I want to make sure.

The code you gave me will be the "profile.php" php file right? So I edit the HTML part with my template, and depending on the ID the variables will change. Once I edit it, I simply upload the it as profile.php and then when I click the link it will call http://www.davasso.com/clients/fcb/profile.php?id=(value of id)
I think I finnaly feel like its clicking.

I do have one problem though, and I had this problem before when I added "city" and "state" into the scenario (when I first followed the Map API guide, it only used "name" and "address").

I currently get http://www.davasso.com/clients/fcb/profile.php?id=null when I click the link. Which is most likely same problem I had before when I used the other method and got http://www.davasso.com/clients/fcb/locations/null/null/name

My problem is, when I got it to work the last time I didnt exactly figure out how I got it to work. It edit the code by adding "city" and "state" in areas where it looked like they should be but it still didnt work. I left my computer, came back 10 minutes later, and it was suddenly working, so I still dont know how I fixxed it. I tried adding "id" in the same areas I added "city" and "state", but still no luck.

I know you have some experience with the Map API, so maybe you know a solution?

Here are the areas I added the "id" value.


var bounds = new GLatLngBounds();
       for (var i = 0; i < markers.length; i++) {
         var id = markers[i].getAttribute('id');
         var name = markers[i].getAttribute('name');
         var address = markers[i].getAttribute('address');
         var state = markers[i].getAttribute('state');
         var city = markers[i].getAttribute('city');
         var distance = parseFloat(markers[i].getAttribute('distance'));
         var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')),
         var marker = createMarker(point, id, name, address, state, city);
         var sidebarEntry = createSidebarEntry(marker, name, address, distance);
       map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));

    function createMarker(point, id, name, address, state, city) {
      var marker = new GMarker(point);
      var html = '<b>' + name + '</b> <br/>' + address + '<br />' + '<a href=\"profile.php?id=' + id  + '\">View Profile</a>' + '&nbsp;' + '&nbsp;';
              // ======== Add a "directions" link ======
        html += ' <a href="http://maps.google.com/maps?saddr=&daddr=' + point.toUrlValue() + '" target ="_blank">Directions<\/a>';

      GEvent.addListener(marker, 'click', function() {
      return marker;

and my xml generator

// Search the rows in the markers table
$query = sprintf("SELECT id, address, name, state, city, lat, lng, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < '%s' ORDER BY distance LIMIT 0 , 20",
$result = mysql_query($query);

if (!$result) {
  die("Invalid query: " . mysql_error());

// Iterate through the rows, adding XML nodes for each
while ($row = @mysql_fetch_assoc($result)){
  $node = $dom->createElement("marker");
  $newnode = $parnode->appendChild($node);
  $newnode->setAttribute("id", $row['id']);
  $newnode->setAttribute("name", $row['name']);
  $newnode->setAttribute("address", $row['address']);
  $newnode->setAttribute("state", $row['state']);
  $newnode->setAttribute("city", $row['city']);
  $newnode->setAttribute("lat", $row['lat']);
  $newnode->setAttribute("lng", $row['lng']);
  $newnode->setAttribute("distance", $row['distance']);

echo $dom->saveXML();

Any ideas on where I may be missing it at?

Sorry for double post, the edit button is no longer available to me.

As for it not getting the ID, that is no longer a problem. It took over an hour this time, but it solved itself. Any idea what causes this? Im guessing its the XML refreshing, but im no guru in that area.

My only error now is a small one in the profile script you gave me. Hasnt been edited yet.
"Parse error: syntax error, unexpected $end in /home/davassoc/public_html/clients/fcb/profile.php on line 28",

I matched up the opening and closing curly brackets, and from what I can see they match up.

You are right, curly brackets usually create that error. I don't see the error in the script though.

Hopefully you figured it out.

Yea I figured it out, I just had to move the comment after "HTML;" down a line, and that solved the problem. Everything works though now. I can't tell you how thankfull I am. The process itself is so simple, and I have a much better understanding of the possibilites of PHP now.

So thanks to you, this problem is solved.

One quick final question though? If I wanted to add more PHP functions into my template, is that still possible with my design being stored in a variable, and variables being surrounded by curly brackets?

Depends on what you mean by "PHP functions". Pretty much, all you have to do is put the data you want in your template in a variable and put that variable in the template.

Umm an example would be a search feature, the search option is part of my template, but I am guessing I cannot add PHP opening and closing tags within the html variable. Although I suppose I could run the search form with an action calling a PHP file.

I'll just do my best to find guides and other info related to it, and work things out on my own. If I cant get it to work, after exhausting every resource I can find, I may ask you, but I am finding that the solutions are not as complicated as I think the should be.

Thanks again for all your help.

Templates don't have to be in a variable. You can do something like this:

//code here
<div id="test">Html here <?php echo $variable;?></div>
//search function here
<div>More html, ect.</div>

Alright I'll go ahead and toy around with that idea.