Populating an html form with mysql data.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • fjm
    Contributor
    • May 2007
    • 348

    Populating an html form with mysql data.

    Hi all, thanks for helping. I'm sure what I want to do is amongst the basic in php. I know ehat I need but I really don't where to begin.

    What I have is a basic html form I have made consisting of header fields and fileds that will be populated from a mysql database. here is a small example of the form.

    Code:
    ANIMALS <-header
    dog <-field
    cat <-field
    bird <-field
    
    FRUIT<-header
    apple <-field
    orange <-field
    cherry <-field
    
    HUMANS<-header
    man <-field
    woman <-field
    Can someone point me in the direction I need to go to populate the fields?

    One other problem is that the headers, if there are no coorasponding field values, should be ommited from the html. Again, I have the html form already complete with the headers intact but I don't know how to omit them if there are no field values for that particular header.

    None of this form will need inserts, updates or delete sql. It is simply just a view in a pertty html form.

    Thnaks guys!
  • pbmods
    Recognized Expert Expert
    • Apr 2007
    • 5821

    #2
    What's your MySQL table structure like? How are the headers stored? How are the field values stored?

    My initial reaction would be to set up a template, but this might be tricky depending on how you have your database set up.

    Comment

    • ak1dnar
      Recognized Expert Top Contributor
      • Jan 2007
      • 1584

      #3
      I have the html form already complete with the headers intact but I don't know how to omit them if there are no field values for that particular header.
      Please post this form that you made, then we can find out what you are looking for.

      Comment

      • fjm
        Contributor
        • May 2007
        • 348

        #4
        Originally posted by pbmods
        What's your MySQL table structure like? How are the headers stored? How are the field values stored?
        Hi pbmods, thanks for the response.

        My table structure is broken down to minimally 3nf and some tables are out to 4nf. There are about 45 tables in total but I am only using certain fields for this template I have created.

        The headers are not stored in the database, they are just headers in the html that breaks up the classification of data. For example, the "HUMAN" heading would have height, weight, eye color, etc. Those attributes may be broken out over different tables in the database. Following is some sample html from my template that I would use under a heading of "RESPONSIBL E PERSON". Again, that heading is not stored in the db but is only there to make the html template more readable to the end user.

        The brackets denote where I want the fields to draw from the the db.

        Code:
        Age: {age}
         Cell Phone: {cell phone}
         
        Sex: {sex}
         
        Home Address: {home address}
         Place of Birth: {place of birth}
         
        Apartment: {apartment}
         SSN: {ssn}
         
        City: {city}
         
        State: {state}
         
        Zip: {zip}

        Thanks again for any input.

        Comment

        • fjm
          Contributor
          • May 2007
          • 348

          #5
          Does anyone have a take on this? I'm really stuck here.

          Comment

          • pbmods
            Recognized Expert Expert
            • Apr 2007
            • 5821

            #6
            Originally posted by fjm
            The brackets denote where I want the fields to draw from the the db.

            Code:
            Age: {age}
             Cell Phone: {cell phone}
             
            Sex: {sex}
             
            Home Address: {home address}
             Place of Birth: {place of birth}
             
            Apartment: {apartment}
             SSN: {ssn}
             
            City: {city}
             
            State: {state}
             
            Zip: {zip}
            Congratulations ! You've just designed your first templating system!

            Check this out:

            [code=php]
            $output = '';
            preg_match_all( '{(\w+)}', $template, $tags);
            foreach($mysql_ results as $row => $data) {
            $rowOut = $template;

            foreach($tags[1] as $idx => $tagName)
            $rowOut = str_replace($ta gs[0][$idx], $data[$tagName], $rowOut);

            $output .= $rowOut;
            }
            [/code]

            First, we run through $template and cache all our {tags}.
            Then, for each row in our MySQL results, we run through it and append a processed copy of the $template:

            For each tag that we found before, run through and replace any instances of it with the same-named column in our MySQL data.

            Welcome to the basics of creating your own templating engine. From here, it's up to you (e.g., handling backslashes, attributes, meta-tags, etc.).

            If you don't want to do all that work, you could just use Smarty.

            Comment

            • fjm
              Contributor
              • May 2007
              • 348

              #7
              pbmods, thank you for the vote of confidence on creating my first template system. :) The experience is bittersweet though. You provided the code but I am not really sure where to put it. If I may ask a couple more questions..

              My template is written in html with a .html extension. Right now, there is no php in the html at all. I believe that I would place your code in the html template. Am I correct on this? Of course I have the mysql connection and sql script. I am assuming that I would place all of the code as such:

              Code:
              <?php 
              
              function connectDb($user, $pass, $host, $db) { 
                  //this function connects to a mysql server 
                  $sock = mysql_connect($host, $user, $pass); 
                  
                  //this function connects to a mysql database, once a server has been reached. 
                  if(isset($sock)) { 
                      if(!mysql_select_db($db, $sock)) { 
                          echo mysql_error(); 
                      } 
                  } 
                  return $sock; 
              } 
              
              
              //simple use of the function 
              $socket = connectDb('user','password','localhost','template'); 
              
              //create an sql query 
              $sql = "SELECT *  FROM address LIMIT 10"; 
              
              //perform the query and return a resource identifier to $query 
              $query = mysql_query($sql, $socket); 
              
              //show all the data via a while loop 
              while($data = mysql_fetch_assoc($query)) { 
                  //using foreach, list all the data that was returned in the $data array from mysql_fetch_assoc 
                  foreach($data as $key => $value) { 
                      echo $value.'<br />'; 
                  } 
                  echo '<br />'; 
              } 
              
              ?>
              
              <?php
              
              $output = '';
              preg_match_all('{(\w+)}', $template, $tags);
              foreach($mysql_results as $row => $data) {
                  $rowOut = $template;
               
                  foreach($tags[1] as $idx => $tagName)
                      $rowOut = str_replace($tags[0][$idx], $data[$tagName], $rowOut);
               
                  $output .= $rowOut;
              }
              
              ?>
              <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
              <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
              <head>
                  <titl
              Also I have a question about *where* or rather how the php code you provided will know what db field to insert into the html. For example, my template has 106 fields that need to be populated with db info. How does the php code know, for example to insert the data that equals "man" into the template in the correct spot?

              I know this may sound really dumb but I was originally thinking about creating 106 different sql select statements and placing that variable into the correct spot in my template. See.. stupid huh. :)

              Please forgive my ignorance but when I say newbie I mean N-E-W-B-I-E. :)

              Thanks again for the help and patience!!

              Comment

              • pbmods
                Recognized Expert Expert
                • Apr 2007
                • 5821

                #8
                Originally posted by fjm
                My template is written in html with a .html extension. Right now, there is no php in the html at all. I believe that I would place your code in the html template. Am I correct on this? Of course I have the mysql connection and sql script. I am assuming that I would place all of the code as such:
                Think of it like this: In your template, all you're worrying about is the structure. So if you had a (simple) template that looked like this:

                [code=html]
                <div id="{recordid}" >My name is {name}. I like {fruit}s.</div>
                [/code]

                The idea here is that we will take that template and parse it once for every entry in your search results. So if you ran a MySQL query, and you got back these results:

                [code=php]
                array(
                0 => array(
                'recordid' => 1,
                'name' => 'Peter',
                'fruit' => 'apple'
                ),

                1 => array(
                'recordid' => 2,
                'name' => 'Paul',
                'fruit' => 'orange'
                ),

                2 => array(
                'recordid' => 3,
                'name' => 'Mary',
                'fruit' => 'artificial strawberry'
                )
                );
                [/code]

                The goal is to end up with this after you run the template/content through your engine:

                [code=html]
                <div id="1">My name is Peter. I like apples.</div>
                <div id="2">My name is Paul. I like oranges.</div>
                <div id="3">My name is Mary. I like artificial strawberrys.</div>
                [/code]

                Well, close enough. What do computers know about strawberrys, anyway?

                At any rate, the point here is that you want to keep your template separate from your content. Your template doesn't know [/ doesn't care] about the content. All it does is tell you where the tags go. Your content doesn't care about your template; all it does is tell you what you're working with.

                All the template engine has to do is match up tags to data and merge them properly.

                So... suppose you create this nifty little template and you store it in an HTML file (which is a perfectly acceptable way to do it; after all, you might want to use it with more than one page). How do you get at it?

                Why do we love PHP? Because there's a function for EVERYTHING!

                [code=php]
                $template = file_get_conten ts('template.ht ml');
                [/code]



                Originally posted by fjm
                Also I have a question about *where* or rather how the php code you provided will know what db field to insert into the html. For example, my template has 106 fields that need to be populated with db info. How does the php code know, for example to insert the data that equals "man" into the template in the correct spot?
                You have two options. The easy way (and the way the code I gave you is set up) is to use the same name for your tags as the DB field that you want. So in other words, {name} would correspond to the 'name' field from your results.

                Mapping arbitrary tag names to field names (or functions!) would require a third array, and that's probably getting a little more complicated than you're looking for.

                Incidentally, while we're on the subject of reinventing the wheel, you are welcome to check out Smarty, which is a very nice templating system that has already been developed.

                I'm happy with everything I've learned (if the hard way) by developing my own (maybe I should call it Brillant...), and I'm sure you will, too. But it's going to take awhile to get it right.

                Originally posted by fjm
                I know this may sound really dumb but I was originally thinking about creating 106 different sql select statements and placing that variable into the correct spot in my template. See.. stupid huh. :)
                You should have seen my code before learned what object-oriented programming is. Same concept.

                Originally posted by fjm
                Please forgive my ignorance but when I say newbie I mean N-E-W-B-I-E. :)
                We've all been there. You teach me some patience, and I'll teach you some code.

                Comment

                • fjm
                  Contributor
                  • May 2007
                  • 348

                  #9
                  pbmods,

                  Well, I wish I could say I had luck getting it to work. Its gonna be a very long road I can see and yet I have so much more work to do on this.

                  Let me ask you this, my template file is in the form of template.html, *not* .php. So any php tags I put into the html will not be parsed. The code below you gave me, I put into a seperate php file and called it foo.php.

                  The
                  Code:
                  $template = file_get_contents('template.html');
                  I have edited my html as well to include the exact field names from the db but still no go. I have ran both the template.html and foo.php files and get no change. I do however get my output from the database in this form:

                  Code:
                  1000
                  
                  
                  
                  
                  
                  77077
                  1
                  
                  1001
                  
                  
                  
                  
                  
                  71006
                  2
                  
                  1002
                  What am I doing wrong? Thanks again for the guidence.
                  Also, I could use smartie, but I wouldn't learn anything about php. I figure since I have a real need to complete this form, I should'nt take the easy way out. :)

                  Comment

                  • fjm
                    Contributor
                    • May 2007
                    • 348

                    #10
                    I forgot to include the contents of the foo.php file:

                    Code:
                    <?php 
                     
                    function connectDb($user, $pass, $host, $db) { 
                        //this function connects to a mysql server 
                        $sock = mysql_connect($host, $user, $pass); 
                        
                        //this function connects to a mysql database, once a server has been reached. 
                        if(isset($sock)) { 
                            if(!mysql_select_db($db, $sock)) { 
                                echo mysql_error(); 
                            } 
                        } 
                        return $sock; 
                    } 
                     
                     
                    //simple use of the function 
                    $socket = connectDb('usa','password','usa.com','ffl'  ); 
                     
                    //create an sql query 
                    $sql = "SELECT *  FROM address where address_Seq = '1'"; 
                     
                    //perform the query and return a resource identifier to $query 
                    $query = mysql_query($sql, $socket); 
                     
                    //show all the data via a while loop 
                    while($data = mysql_fetch_assoc($query)) { 
                        //using foreach, list all the data that was returned in the $data array from mysql_fetch_assoc 
                        foreach($data as $key => $value) { 
                            echo $value.'<br />'; 
                        } 
                        echo '<br />'; 
                    } 
                     
                    ?>
                     
                    <?php
                    $template = file_get_contents('test.html');
                    $output = 'test.html';
                    preg_match_all('{(\w+)}', $template, $tags);
                    foreach($mysql_results as $row => $data) {
                        $rowOut = $template;
                     
                        foreach($tags[1] as $idx => $tagName)
                            $rowOut = str_replace($tags[0][$idx], $data[$tagName], $rowOut);
                     
                        $output .= $rowOut;
                    }
                     
                    ?>
                    Here is the contents of the test.html file:

                    Code:
                    <div id="{address_Seq}">The license Number is {license_Number}.</div>
                    I am looking at the code and am not sure if I may see the problem, but does the line $mysql_results have anything to do with the template not being parsed? I mean, if I am reading the connection code properly, the results are output to a variable called $value.

                    I changed that variable in your code to $value but it still didn;t work. I'm trying. :)

                    Comment

                    • rfresh
                      New Member
                      • May 2007
                      • 2

                      #11
                      @fjm

                      Maybe I'm over simplfying this, but why don't you just populate your web page HTML objects from your DB after fetching their values? I would just populate your HTML objects directly from the DB fields; something like this:

                      Code:
                      $frm_name = $php_row->name;

                      Comment

                      • fjm
                        Contributor
                        • May 2007
                        • 348

                        #12
                        rfresh,

                        Thanks for the pointer. Do you mean to have the html dynamically generated?

                        Comment

                        • Motoma
                          Recognized Expert Specialist
                          • Jan 2007
                          • 3236

                          #13
                          I posted a fantastic tutorial that has an example of populating an HTML table from a database.

                          Comment

                          • fjm
                            Contributor
                            • May 2007
                            • 348

                            #14
                            Originally posted by Motoma
                            I posted a fantastic tutorial that has an example of populating an HTML table from a database.
                            Thank you Motoma. I will definately have a look at that! I really appriciate everyone that is taking the time to help me! Thanks guys!

                            Hey Motoma, I get this message in my php log:
                            Code:
                            Cannot instantiate non-existent class:
                            I googled it and continually come up with issures relating to permissions. Both of your files have read/write access and still nothing. Any ideas?

                            Comment

                            • Motoma
                              Recognized Expert Specialist
                              • Jan 2007
                              • 3236

                              #15
                              Originally posted by fjm
                              Thank you Motoma. I will definately have a look at that! I really appriciate everyone that is taking the time to help me! Thanks guys!

                              Hey Motoma, I get this message in my php log:
                              Code:
                              Cannot instantiate non-existent class:
                              I googled it and continually come up with issures relating to permissions. Both of your files have read/write access and still nothing. Any ideas?
                              What class are you having difficulties instantiating? If you follow the post at the top of the Forum about enabling error messages, you will be given this information.

                              Comment

                              Working...