I'm new to relational database programing and PHP (I used to do Lotus Notes db - decidely not relational)

I dont want to start bad habits with my relationship db design and so i'm asking for help with the following design scendario:

I have a form where the user is defining elements of a workout. For example:

  1. Chest Press, 12 reps, 3 sets
  2. Lower Back extension, 12 reps, 3 sets
  3. Bicept Curl, 12 reps, 3 sets

So I figure I'll need to create a parent record with the username and the name of the workout. Then for each row of data the user entered in the grid i'll need to create children document that has fields for the excecise, the reps and the sets.

So then I need put the parents record ID on all the children (row) records.

So the field on the parent record is 'ID' and it is not set until the record is saved in MySQL. I need to set the same field in all the children records to creat the relationship.

I'm kinda at a loss about how i should code this. The most obvious way would be to save the parent record first to get that field set from the autoincrement.

So then do i need to do a query to get the field value? Then save the children records?

This strikes me as unelegant.

How should I handle this? Am I approaching the challenge fundamentally wrong?

    Your question is broad, so it's hard to troubleshoot your idea. You may be better off starting with one of many online tutorials regarding PHP/MySQL, do some practice code, and then come back here when you have a specific problem that you're stuck on. Then someone can troubleshoot a specific problem.

    Maybe try the following link, but of course there are many others like it if you Google.

    http://www.sitepoint.com/article/php-amp-mysql-1-installation

      I dont think it's broad at all, and i've been thru the tutorials.

      Is thi forum only for when you've hit a brick wall or is it also for advice?

      Beacuse I dont have a problem per se. I'm looking for advice on how to structure my database, regarding this parent-child multiple row where i need to set the key to create the relationship.

      Should I use the autoincrement option or should i generate a key to link them together??? What kind of function shoulud I use to generate the unique key? My question relates to setting these keys. I really dont know how you could think my question was broad!

      Originally posted by rachel2004
      Your question is broad, so it's hard to troubleshoot your idea. You may be better off starting with one of many online tutorials regarding PHP/MySQL, do some practice code, and then come back here when you have a specific problem that you're stuck on. Then someone can troubleshoot a specific problem.

      Maybe try the following link, but of course there are many others like it if you Google.

      http://www.sitepoint.com/article/php-amp-mysql-1-installation

        mysql_insert_id() returns the ID generated for an AUTO_INCREMENT column by the previous INSERT query using the given link_identifier. If link_identifier isn't specified, the last opened link is assumed.

          is all hte information being inputted all at once? or does each user get to come back and update.. i think you have the right idea though.. myself i would do

          Table - users

          id - primary, auto incrementing
          name - varchar (20)
          password - ( you can either varchar or encrypt this )
          etc.. any other info

          Table - workout

          id - primary, auto incrementing
          user_id - int(11)
          workout_name - varchar(100)
          workout_reps - int(11);
          workout_sets - int(11);
          etc.. any other info

            You wrote:

            The most obvious way would be to save the parent record first to get that field set from the autoincrement.

            That's right.

            So then do i need to do a query to get the field value? Then save the children records?

            That's right, too.

            This strikes me as unelegant.

            Right again. You're 3 for 3!

            How should I handle this? Am I approaching the challenge fundamentally wrong?

            Sometimes one is forced to do the inelegant.

            What I do to make things more elegant is to create a single SEPARATE table with an auto increment column to create unique parent ids -- then use a little function to capture that new id..

            $parentid=uniqueid();

            Then
            INSERT into parentTable SET id=$parentid

            INSERT into childTable SET parentid=$parentid

            It's exactly the same, really, but it feels a little more elegant.

              Originally posted by everknown
              Should I use the autoincrement option or should i generate a key to link them together??? What kind of function shoulud I use to generate the unique key? My question relates to setting these keys. I really dont know how you could think my question was broad!

              Sorry about that... I obviously dropped the ball on this one. I'll try to make sure I am better at reading every word someone posts and then just as quickly visit the PHP and MySQL manual to save them the trouble of having to look it up themselves. You would think that somewhere in all of that, the poster would be more tolerant of any oversights on my part, but true, I best read better and research harder since you pay me so well for my time. Thanks for keeping me in check, sir.

                Why the need for insulting sarcasm? Because i wanted to know why you thought my post was too broad?

                Originally posted by rachel2004
                Sorry about that... I obviously dropped the ball on this one. I'll try to make sure I am better at reading every word someone posts and then just as quickly visit the PHP and MySQL manual to save them the trouble of having to look it up themselves. You would think that somewhere in all of that, the poster would be more tolerant of any oversights on my part, but true, I best read better and research harder since you pay me so well for my time. Thanks for keeping me in check, sir.

                  Originally posted by nemonoman
                  You wrote:

                  What I do to make things more elegant is to create a single SEPARATE table with an auto increment column to ....

                  Extra table is not more elegant.

                    Maybe not, but that's how Oracle does it -- or did it in versions 3-7.

                    And as I say later in my note:

                    It's exactly the same, really, but it feels a little more elegant.

                      nemonoman, I'm not trying to challenge your knowledge on this because I know you're strong on SQL statements/MySQL as I've seen in your other posts. My question is regarding your using the uniquID() function versus just doing it with mysql_insert_id(). When I've been forced to resolve issues where I need to take a Table1's id and insert that into a table that needs to be linked back to Table1, I've used the mysql_insert_id() function. So when I add a record and assuming there is only one table linked back to Table1, I'm required to perform 2 INSERTs: one for Table1 and one for the linked table. However, I don't require a third table with this approach.

                      My question: is choosing to do it with a third table and with the uniquid() function a performance reason? I haven't tried benchmarking it yet... wanted to solicit your opinion. Thanks in advance for your feedback.

                        I am certifiably among the oldest codgers attending this forum. I suppose I was one of the first persons to program Oracle in a client/server environment using 4th Dimension as a front end.

                        About the time I got into RDBMSs, Oracle developed sequences.

                        INSERT INTO myTable SELECT mysequence.nextval FROM dual
                        INSERT INTO childTable SELECT mysequence.currval from dual

                        Previously they had used 'nextnum' tables which operated similarly.

                        I have built a similar method into my database. I keep separate unique id tables for most of my primary keys.

                        I'm just used to doing it, and it's easy enough to build and maintain.

                        
                        
                        function uniquekey($type) {
                        
                        //usage: $myProductID=uniquekey('product');
                        //returns next ID in sequence from special table
                        //if no sequence table exists, builds the table
                        //uses a couple of handbuilt functions:
                            //getuser()provides unique userinfo stored in cookie
                             //(any uniqueinfo would do)
                        //dosql() connects to the database and returns the result of a query
                        
                           $table = 'unique'.$type.'id';
                        $theuser = getuser();
                          $thequery  .= "   INSERT INTO $table
                                              SET         name = '$theuser'";
                           $result = dosql($thequery);
                           if ((!$result) && (mysql_errno() == 1146)) {
                        //error 1146 means "no table by that name", 
                        //so we'll create the unique.$type.id table now:
                                   $result = dosql("
                                       CREATE TABLE $table (id int(11) NOT NULL auto_increment,
                                       name varchar(70) default NULL,
                                       PRIMARY KEY  (id)) ");
                                   $result = dosql($thequery);
                                 dosql("INSERT into $table set id=1");
                               }
                               $uniqueid = mysql_insert_id() ;
                              $thequery="DELETE FROM $table where id=$uniqueid";
                               $result = dosql($thequery);
                               return $uniqueid;
                           }
                        

                        Some other codger on another board created a similar method independently, because, as he said, this method was easily portable between different DB vendors.

                        $parentkey=uniquekey('parent');
                        $childkey=uniquekey('child');
                        $user=getuser();
                        mysql_query("INSERT INTO parent SET id=$parentkey");
                        mysql_query("INSERT INTO child SET id=$childkey, parentid=$parentkey, user=$user");
                        //etc.
                        

                        The simplicity of reading the code above (since I'm constantly screwing up and needing to debug) beats the pants off INSERT INTO parent, $parentkey=mysql_last_insert_id(); etc.

                        for example, without realizing it, code like this could easily get broken:

                        mysql_query("INSERT INTO parent SET id=NULL");
                        $user=getuser();
                        $parentkey=mysql_last_insert_id();
                        mysql_query("INSERT INTO child SET id=NULL, parentid=$parentkey, user=$user");
                        

                        This code worked fine UNTIL I changed getuser();
                        As part of getuser() I added code to insert a userrecord with a timestamp. So $parentkey=mysql_last_insert_id(); sets $parentkey to the last id of userrecord, not parentTable.

                        For awhile I actually had "currval(type)" and "nextval(type)" functions -- that's why the code above contains 'getuser()', which strictly speaking is no longer necessary -- but since most of my INSERT or UPDATE work was being done in a single script, I just compressed it to the function above: I get the unique key and use it for all subsequent SQL.

                        So that's how an old codger does it.

                        Perhaps my history will also explain why I differentiate very hard between doing work through SQL and doing work through PHP.

                        It is my experience that NEARLY ANYTHING that can be done with SQL is orders of magnitude faster than nearly anything that can be done by having PHP manipulate the results.

                        This is why, for example, I work date management through SQL whenever possible; and also string searches and manipulation, and value updates, etc. , etc.

                        It's very tough to learn several languages, and SQL isn't pretty, but understanding and knowledge of various languages increases the programmer's ability to pound the living shit out of pesky problems by choosing the right method for the job.

                        PS: the code above is not in anyway related to PHP's uniquid() function...however you could use that function to replace 'getuser()' in the above code.

                          Originally posted by nemonoman
                          It is my experience that NEARLY ANYTHING that can be done with SQL is orders of magnitude faster than nearly anything that can be done by having PHP manipulate the results.

                          This is why, for example, I work date management through SQL whenever possible; and also string searches and manipulation, and value updates, etc. , etc.

                          Actually I've noticed in your posts that you solve a lot of your problems in the SQL statements vice the PHP code. I've reponded to a few posts where you've also responded and I think there was one from over the weekend or late last week where I gave the answer using the mktime() or date() PHP functions and you gave an equivalent answer via MySQL functions. I'll keep your generalization in mind about the speed of SQL statements vice coding in PHP when I approach a problem and attempt to solve it. I may have to force myself to "un-learn" some things to adapt. I appreciate your time in posting back this morning to my question.

                            When I first started DB programming I also was familiar with the procedural language, and treated the database as sort of a big hard drive for storing values which I manipulated in the client.

                            It took a big step for me to realize that the DB was smart; in many cases smarter than the procedural language.

                            My development group contained a couple old codgers who'd never programmed in anything but SQL. They were amazed by how I could manipulate results for pretty displays and user interfaces.

                            For example: Non-repeating titles. SQL just returns

                            Yankees vs Dodgers Game 1Score 5-3
                            Yankees vs Dodgers Game 2 Score 6-3
                            Yankees vs Dodgers Game 3 Score 1-3
                            Yankees vs Reds Game 1 Score 13-3
                            Yankees vs Reds Game 2 Score 13-3
                            Phillies vs Reds Game 1 Score 3-4

                            PHP can manipulate:

                            Yankees

                             vs Dodgers

                               Game 1 Score 5-3
                               Game 2 Score 6-3
                               Game 3 Score 1-3
                              vs Reds
                               Game 1 Score 13-3
                               Game 2 Score 13-3
                            Phillies
                              vs Reds
                               Game 1 Score 3-4

                            On the other hand this construction

                            SELECT sum(IF(WEEK(timestamp)=1,amount,0)) as week1
                            sum(IF(WEEK(timestamp)=2,amount,0)) as week2

                            etc...
                            which summarizes amount depending on week (great for invoice reports, etc.)

                            is a kinghellbitch to do using standard PHP functions, but a breeze using SQL

                              Write a Reply...