Jump to content


Photo

Chapter 8 - Few Questions


  • Please log in to reply
14 replies to this topic

#1 raphk

raphk

    Active Member

  • Members
  • PipPip
  • 12 posts

Posted 08 July 2009 - 11:02 AM

I'm trying to figure out how the primary key <-> foreign key relationship works...

My main question being, are 'foreign keys' a METHOD of referencing table data between tables by using a primary key as a reference, or is this some sort of option (or attribute) you must set within mysql when creating tables for it to properly work? For me, the book does not do a great job at explaining this and since it tells me to just dump the schema from the downloaded examples, I'm very unclear how this works.

I'm also unclear on arrays, the book mentions it but not does explain it fully. An array is a collection of data put into a variable?

Sometimes i find this book using code that is not explained, here is a snippet:
CODE
// Generate the questionnaire form by looping through the response array
  echo '<form method="post" action="' . $_SERVER['PHP_SELF'] . '">';
  echo '<p>How do you feel about each topic?</p>';
  $category = $responses[0]['category_name'];
  echo '<fieldset><legend>' . $responses[0]['category_name'] . '</legend>';
  foreach ($responses as $response) {
    // Only start a new fieldset if the category has changed
    if ($category != $response['category_name']) {
      $category = $response['category_name'];
      echo '</fieldset><fieldset><legend>' . $response['category_name'] . '</legend>';
    }

    // Display the topic form field
    echo '<label ' . ($response['response'] == NULL ? 'class="error"' : '') . ' for="' . $response['response_id'] . '">' . $response['topic_name'] . ':</label>';
    echo '<input type="radio" id="' . $response['response_id'] . '" name="' . $response['response_id'] . '" value="1" ' . ($response['response'] == 1 ? 'checked="checked"' : '') . ' />Love ';
    echo '<input type="radio" id="' . $response['response_id'] . '" name="' . $response['response_id'] . '" value="2" ' . ($response['response'] == 2 ? 'checked="checked"' : '') . ' />Hate<br />';
  }
  echo '</fieldset>';
  echo '<input type="submit" value="Save Questionnaire" name="submit" />';
  echo '</form>';

  // Insert the page footer
  require_once('footer.php');


so from the above script:
CODE
echo '<fieldset><legend>' . $responses[0]['category_name'] . '</legend>';

what exactly does the [0] within $responses[0]['category_name'] do? my browser complains about it as well:
QUOTE
Notice: Undefined offset: 0 in /home/raph/www/php_learning/examples/ch08/initial/mismatch/questionnaire.php on line 74


Next..
CODE
// If the questionnaire form has been submitted, write the form responses to the database
  if (isset($_POST['submit'])) {
    // Write the questionnaire response rows to the response table
    foreach ($_POST as $response_id => $response) {
      $query = "UPDATE mismatch_response SET response = '$response' WHERE response_id = '$response_id'";
      mysqli_query($dbc, $query);
    }
    echo '<p>Your responses have been saved.</p>';
  }


From the above snippet
CODE
foreach ($_POST as $response_id => $response)

I have no idea what this is doing.. taking every piece of data from the post array, putting it into $response_id and into $reponse?? very confused sad.gif

how about array_push?
CODE
  while ($row = mysqli_fetch_array($data)) {
      array_push($topicIDs, $row['topic_id']);
    }

This loops through the $data array, and for every $topicIDs it finds it places into the $row array under topic_id? I know it briefly explains array_push on page 449, but i'm still unclear as to how it works

Lastly, when i use the code provided at http://www.headfirst...om/books/hfphp/ for the questionnaire.php, when I try to use this it does not list anything, i have attached an image with exactly what i see, and the current scheme of my database (had to change extension to .txt or else would not upload)

Any help would be greatly appreciated..

Attached Thumbnails

  • hfphpch8error.PNG

Attached Files



#2 raphk

raphk

    Active Member

  • Members
  • PipPip
  • 12 posts

Posted 08 July 2009 - 12:08 PM

After some poking around, i figured out why questionnaire.php was failing for me.

the reason i was getting a page with no data for the questionnaire was because the database schema for mismatch_topic (mismatch_topic.sql) in examples\ch08\page443 creates the wrong column name "category" where it should be "category_id", as it is referenced throughout the script.

however, the mismatch_topic.sql in examples\ch08\final does create the correct column. I can't believe no one else had an issue with this?

#3 lemuel

lemuel

    Super Veteran Member

  • Members
  • PipPipPipPipPipPipPipPipPipPipPip
  • 577 posts

Posted 08 July 2009 - 07:04 PM

QUOTE (raphk @ Jul 8 2009, 12:08 PM) <{POST_SNAPBACK}>
the reason i was getting a page with no data for the questionnaire was because the database schema for mismatch_topic (mismatch_topic.sql) in examples\ch08\page443 creates the wrong column name "category" where it should be "category_id", as it is referenced throughout the script.

however, the mismatch_topic.sql in examples\ch08\final does create the correct column. I can't believe no one else had an issue with this?


Listed at least three times in Unconfirmed errata

#4 lemuel

lemuel

    Super Veteran Member

  • Members
  • PipPipPipPipPipPipPipPipPipPipPip
  • 577 posts

Posted 08 July 2009 - 07:12 PM

QUOTE (raphk @ Jul 8 2009, 11:02 AM) <{POST_SNAPBACK}>
how about array_push?
CODE
  while ($row = mysqli_fetch_array($data)) {
      array_push($topicIDs, $row['topic_id']);
    }

This loops through the $data array, and for every $topicIDs it finds it places into the $row array under topic_id? I know it briefly explains array_push on page 449, but i'm still unclear as to how it works


For every record found append the contents of the 'topic_id' field to the array $topicIDs.

#5 raphk

raphk

    Active Member

  • Members
  • PipPip
  • 12 posts

Posted 09 July 2009 - 07:32 AM

thanks for the replies lemuel!

if people are complaining about this 'errata' for months why haven't they changed one dumb line in their sample code, saving their customers possible hours? unbelievable..

do you think you can share any insight into if the relationship between primary keys and foreign keys are just a method of referencing data, or is it an actual function of mysql?

thanks again



#6 raphk

raphk

    Active Member

  • Members
  • PipPip
  • 12 posts

Posted 09 July 2009 - 09:33 AM

here's a great article in case anyone is wanting to better understand primary keys & foreign key relationship
http://c7y.phparch.c...n_keys_in_mysql

Basically before InnoDB this foreign key relationship was theoretical, but now it's part of MySQL and you can use it to ensure data integrity between your tables, particularly helpful from the above link:

QUOTE
By just declaring the foreign key, we now have some built in protection for our data integrity. If we try to INSERT or UPDATE one of our foreign key values in invoice, the database will automatically check the table it connects to and make sure the value already exists in that table. If the value does not exist in the referenced table, the database will reject the INSERT/UPDATE and protect your data for you.


From the examples in the book, the schema is not making use of the FOREIGN KEY attribute for linked tables, instead just outlining the method for referencing data between tables to eliminate duplicate data

Edited by raphk, 09 July 2009 - 09:35 AM.


#7 Berkamin

Berkamin

    New Member

  • Members
  • Pip
  • 4 posts

Posted 10 September 2009 - 02:22 AM

I second the question about the code on bottom of page 448.
CODE
foreach($_POST as $response_id => $response){...}

What is this supposed to mean? I looked up the introduction to "foreach" in the index, but nothing explains what the => is. Is this supposed to be a comparison (equal to or greater than) or an arrow? If it is an arrow, why hasn't this been introduced, and why isn't there anything in the index about this symbol?

Also, where is $response from? The notes in the code on page 448 need to explain where the variables are from, or it just leaves the user confused.

Edited by Berkamin, 10 September 2009 - 02:24 AM.


#8 28Mikes

28Mikes

    New Member

  • Members
  • Pip
  • 1 posts

Posted 18 September 2009 - 11:59 AM

Does anyone have a working questionnaire script on Page 443, 448 and 456. Mine is failing to work despite changing the script. Thanks

#9 geoffrey.brown

geoffrey.brown

    Active Member

  • Members
  • PipPip
  • 32 posts

Posted 14 January 2011 - 11:19 AM

If the responder is still around, I'd like to know more. I'm trying to set up a small database for the first time outside this book that uses concepts taught in the book and I found that I'm confused about how to implement and use foreign keys. I grasp the concept, but as the original poster stated, the book isn't real clear on this point.

I just tried to access the link cited below, but unfortunately my browser was unable to bring it up.

I'd love a more experienced opinion, if anyone has one.

Cheers,

Geoffrey

QUOTE (raphk @ Jul 9 2009, 09:33 AM) <{POST_SNAPBACK}>
here's a great article in case anyone is wanting to better understand primary keys & foreign key relationship
http://c7y.phparch.c...n_keys_in_mysql

Basically before InnoDB this foreign key relationship was theoretical, but now it's part of MySQL and you can use it to ensure data integrity between your tables, particularly helpful from the above link:



From the examples in the book, the schema is not making use of the FOREIGN KEY attribute for linked tables, instead just outlining the method for referencing data between tables to eliminate duplicate data



#10 Andruss

Andruss

    New Member

  • Members
  • Pip
  • 2 posts

Posted 18 February 2012 - 01:19 PM

Well it's a two dimensional array for example a[0]=6 a[1]=7 a[2]=8 and etc.That code saying that for superglobal $_POST (which take values from form) grub and present all values as following $response_id as a[0] and values will be => 6,7 and 8 as variable $response.If still not clear google "two dimensional array+php"
However i got the problem with
sql doesn't want to run the query saying there is error in it,something wrong with that statement so $_POST should be as $_POST['response'] or even as array $responses but even after changing it to
($responses as $response_id=>$response)
i still can't get and Updat the mismatch_response table anyone??????

I second the question about the code on bottom of page 448.
<div class='codetop'>CODE</div><div class='codemain' style='height:200px;white-space:pre;overflow:auto'>foreach($_POST as $response_id => $response){...}</div>
What is this supposed to mean? I looked up the introduction to "foreach" in the index, but nothing explains what the => is. Is this supposed to be a comparison (equal to or greater than) or an arrow? If it is an arrow, why hasn't this been introduced, and why isn't there anything in the index about this symbol?

Also, where is $response from? The notes in the code on page 448 need to explain where the variables are from, or it just leaves the user confused.



#11 djphinesse

djphinesse

    Active Member

  • Members
  • PipPip
  • 16 posts

Posted 04 April 2012 - 08:31 AM

Next..
<!--c1--><div class='codetop'>CODE</div><div class='codemain'><!--ec1--> // If the questionnaire form has been submitted, write the form responses to the database
if (isset($_POST['submit'])) {
// Write the questionnaire response rows to the response table
foreach ($_POST as $response_id => $response) {
$query = "UPDATE mismatch_response SET response = '$response' WHERE response_id = '$response_id'";
mysqli_query($dbc, $query);
}
echo '<p>Your responses have been saved.</p>';
}<!--c2--></div><!--ec2-->


Try to break all of it down in your head using what you've already learned.

foreach loops through arrays. the $_POST is super global array, so its getting some information from the form. Now you know you need to go to the form for more clues. You can see that the form uses the response_id and response. the data structure of the table tells us that each response in the table requires an id.

so, the foreach loop is taking all the responses from the form ($_POST) and updating them according to the response id. the response_id is coming from the form values which was generated by the database using a multi-dimensional array. You need a two-dimensional arrary because you need both the response_id and the response to be updated in the database.

So, its saying set 'yes' where response_id is 15.

Hope that helps a little bit.

Edited by djphinesse, 04 April 2012 - 08:33 AM.


#12 Miki@

Miki@

    New Member

  • Members
  • Pip
  • 1 posts

Posted 16 May 2012 - 04:50 AM

Hello,

I just have seen the same error messages, even using the code from the downloaded files. About a half hour of checking I figured out that it is cause by a litte mistyping in the code (even in the downloded and in the printed one in the book).
The problem is where the code tries to read the topic ids from the database.
The wrong line is:
$query = "SELECT topic_id FROM mismatch_topic ORDER BY category_id, topic_id";

The problem is there is no column in the database called "category_id". Corretly it is just "category". Correct it, and it should work fine. :)

I also tried to show it to the authors, but I could not find a way to post this mistake directly to them.

#13 rhender

rhender

    Active Member

  • Members
  • PipPip
  • 10 posts

Posted 26 August 2012 - 05:15 PM

After some poking around, i figured out why questionnaire.php was failing for me.

the reason i was getting a page with no data for the questionnaire was because the database schema for mismatch_topic (mismatch_topic.sql) in examples\ch08\page443 creates the wrong column name "category" where it should be "category_id", as it is referenced throughout the script.

however, the mismatch_topic.sql in examples\ch08\final does create the correct column. I can't believe no one else had an issue with this?


wow, yes... I was having the same issue... I'm glad I found this post.

On line 29 of questionnaire.php, I changed category_id to category... and that immediately solved the problem. The questionnaire form was then generated just fine.

You saved me a lot of time. Thanks for posting this.

#14 TheSnark

TheSnark

    New Member

  • Members
  • Pip
  • 1 posts

Posted 07 September 2012 - 04:00 AM

OK, regarding the following piece on line 47:
foreach ($_POST as $response_id => $response) {

It's not explained in the book, but I think I understand it. Would love to have someone more advanced confirm that I have it correct.

Each input field in our form has an id/name. As in
<input type="text" id="key" name="key" />
. In previous exercises, we would put the user-supplied responses into our PHP code this way:
$value = $_POST['key']
. The $_POST array is two-dimensional, storing the field name/id and value as key=>value.

In this instance, instead of creating a named variable for each form field, we loop through each field's key/value pair, with the key being the field's name/id (response_id) and the value being what the user entered.

If I go to questionnaire.php in my browser, and look at the source, I might see this for the first field:

<label class="error" for="52">Tattoos</label><input type="radio" id="52" name="52" value="1" />Love <input =type="radio" id="52" name="52" value="2" />Hate<br />

As I said, the $_POST array is stored like this: key=>value. So
$_POST['52']
would get you a "1" if the user selected "Love". But, since the response_id changes from user to user and field to field, we store both the value and the key as variables:
$_POST as $response_id => $response
.

It was a big "ah hah" moment when I figured that out. Hope it helps others.

#15 Itjustcomestome

Itjustcomestome

    New Member

  • Members
  • Pip
  • 2 posts

Posted 19 October 2012 - 02:10 PM

I have had some trouble getting logged in to the mismatch web site, I am able to see the index.php page but I can't actually log in as a user. I set my information correctly in the index.php (localhost, username, password, database_name)
Have you had good success with these files yet?




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users