Jump to content

Archived

This topic is now archived and is closed to further replies.

mcloan

help with understanding an array

Recommended Posts

Can some one help me understand this script?  The fetch row was from sql results $results variable.  I think I understand pretty much what this is doing I am just mainly confused on the $row[0].  What does this mean? 

$url_array  = array()
for ($count = 0; $row = $results->Fetch_row(); ++count)
{
    $url_array[$count] = $row[0]
}

Thank you.

Share this post


Link to post
Share on other sites
$row[0] is created from the for loops second parameter (highlighted below):

for ($count = 0; [b]$row = $results->Fetch_row();[/b] ++count)


Looks like $results is a class which calls a method (function) called Fetch_row. Fetch_row returns an array of results from the query that was previously executed. $row[0] will be the first field from the table that was queried.

I cant really explain it as I don't know what's going on. But I'd say that's the basics though.

Share this post


Link to post
Share on other sites
[quote author=wildteen88 link=topic=113051.msg459185#msg459185 date=1162059929]
$row[0] is created from the for loops second parameter (highlighted below):

for ($count = 0; [b]$row = $results->Fetch_row();[/b] ++count)


Looks like $results is a class which calls a method (function) called Fetch_row. Fetch_row returns an array of results from the query that was previously executed. $row[0] will be the first field from the table that was queried.

I cant really explain it as I don't know what's going on. But I'd say that's the basics though.
[/quote]

I got it on the $rows, but there are a couple things else I do not completely understand.  I am learning through a book and I would like to get the concept down before I move on.  The overall script below is basically adding a new bookmark to a web based bookmarking system.  It then gets the urls for a user for sql database and displays them. 

Below is the entire code.  I am having difficulty understanding some of the section I noted above.  This is my issue.  Essentially my understanding is the fetch_row() is returning an array of numbers from the query.  So $row would look something like an array such as (1,2,3,4) etc...  So my first problem is understanding exactly how this for loop is executing.  Normally it would have an end value such as for ($count=0; $count=5; ++count) , but in the code I presented it uses for ($count = 1; $row = $result->fetch_row(); ++$count) and I believe this is an array so I do not exactly understand the $result->fetch_row() criteria for ending the for loop. How does it know when to stop and what number to stop at?

Next I do not understand the $url_array.  My understanding is that it would essentially be a value such as (0,1,2,3) if I understand correctly.  However this $url_array is returned to the orginal script and then passed to function display_user_urls($url_array);.

The function display_user_urls appears to be using $url_array to make the actual booked marked urls be displayed on the screen.  However, how can it do this if the values were never placed into $url_array.  As I stated before I would think the value of $url_array is (1,2,3,4) etc.. from how it was set in the get_users_urls function.

Your assistance with helping me understand this concept is very much appreciated. 

Thank you.


[code]
////  Main Code For .php page
<?php
session_start();

  //create short variable name
  $new_url = $_POST['new_url'];

  do_html_header('Adding bookmarks');
 
  try
  {
    check_valid_user();
    if (!filled_out($_POST))
    {
      throw new Exception('Form not completely filled out.');   
    }
    // check URL format
    if (strstr($new_url, 'http://')===false)
       $new_url = 'http://'.$new_url;

    // check URL is valid
    if (!(@fopen($new_url, 'r')))
      throw new Exception('Not a valid URL.');
    // try to add bm
    add_bm($new_url);
    echo 'Bookmark added.';

    // get the bookmarks this user has saved
    if ($url_array = get_user_urls($_SESSION['valid_user']))
      display_user_urls($url_array);
  }
  catch (Exception $e)
  {
    echo $e->getMessage();
  }
  display_user_menu();
  do_html_footer();
?>


--------------  function begin here------------------

function add_bm($new_url)
{
  // Add new bookmark to the database

  echo "Attempting to add ".htmlspecialchars($new_url).'<br />';
  $valid_user = $_SESSION['valid_user'];
 
  $conn = db_connect();

  // check not a repeat bookmark
  $result = $conn->query("select * from bookmark
                         where username='$valid_user'
                         and bm_URL='$new_url'");
  if ($result && ($result->num_rows>0))
    throw new Exception('Bookmark already exists.');

  // insert the new bookmark
  if (!$conn->query( "insert into bookmark values
                          ('$valid_user', '$new_url')"))
    throw new Exception('Bookmark could not be inserted.');

  return true;
}

function get_user_urls($username)
{
  //extract from the database all the URLs this user has stored
  $conn = db_connect();
  $result = $conn->query( "select bm_URL
                          from bookmark
                          where username = '$username'");
  if (!$result)
    return false;

  //create an array of the URLs
  $url_array = array();
  for ($count = 1; $row = $result->fetch_row(); ++$count)
  {
    $url_array[$count] = $row[0];
  } 
  return $url_array;
}

function display_user_urls($url_array)
{
  // display the table of URLs

  // set global variable, so we can test later if this is on the page
  global $bm_table;
  $bm_table = true;
?>
  <br />
  <form name='bm_table' action='delete_bms.php' method='post'>
  <table width=300 cellpadding=2 cellspacing=0>
  <?php
  $color = "#cccccc";
  echo "<tr bgcolor='$color'><td><strong>Bookmark</strong></td>";
  echo "<td><strong>Delete?</strong></td></tr>";
  if (is_array($url_array) && count($url_array)>0)
  {
    foreach ($url_array as $url)
    {
      if ($color == "#cccccc")
        $color = "#ffffff";
      else
        $color = "#cccccc";
      // remember to call htmlspecialchars() when we are displaying user data
      echo "<tr bgcolor='$color'><td><a href=\"$url\">".htmlspecialchars($url)."</a></td>";
      echo "<td><input type='checkbox' name=\"del_me[]\"
             value=\"$url\"></td>";
      echo "</tr>";
    }
  }
  else
    echo "<tr><td>No bookmarks on record</td></tr>";
?>
  </table>
  </form>
<?php
}
[/code]

Share this post


Link to post
Share on other sites
[quote author=mcloan link=topic=113051.msg459275#msg459275 date=1162072417]
... I do not exactly understand the $result->fetch_row() criteria for ending the for loop. How does it know when to stop and what number to stop at?[/quote]

I was confused for a second when I first looked at that as well, but then realized what was going on. You just need to understand "why" a loop terminates. In this example the loop will iterate 5 times before exeting the loop - but why?
[code]for ($i=0; $i < 5; $i++)[/code]

It exits the loop because the 2nd expression "$i < 5" becomes false. That expression doesn't need to use anything from expression 1 or expression 3. So, in the example yougave the loop will iterate until there are no more rows to fetch (i.e. returns false). It is using the $count to count the number of records there are.

[quote author=mcloan link=topic=113051.msg459275#msg459275 date=1162072417]The function display_user_urls appears to be using $url_array to make the actual booked marked urls be displayed on the screen.  However, how can it do this if the values were never placed into $url_array.[/quote]

They were in this bit of code
[code]// get the bookmarks this user has saved
if ($url_array = get_user_urls($_SESSION['valid_user']))
  display_user_urls($url_array);
}[/code]

This is probably confusing in the same way the previous example was. In the IF statement is is attempting to set the value of $url_array to the value returned from the function "get_user_urls($_SESSION['valid_user'])". That is what is called error handling. If you have an action that *could* fail (and if the action would return false when if fails) you can put it inside the conditional of an IF statement so that you can take an appropriate action if it fails, such as display an error message. The key point is that the action inside the conditional will be acted upon.

Hope this helps.

Share this post


Link to post
Share on other sites
[quote]
It exits the loop because the 2nd expression "$i < 5" becomes false. That expression doesn't need to use anything from expression 1 or expression 3. So, in the example yougave the loop will iterate until there are no more rows to fetch (i.e. returns false). It is using the $count to count the number of records there are.
[/quote]

Thank you.  It helps a lot.  I am starting to get it now.  I totally see how the for loop is ending.  However I am still a little confused on one line in the for loop.

    $url_array[$count] = $row[0];

What exactly is the [$count] for?  I understand the $row[0] is the first field of the query results and the value of this is getting added to $url_array.  But $count starts out at 1 in the for loop so why is it being used here?

Thank you again.

Share this post


Link to post
Share on other sites
actually, $count starts at 0 and then inreases by 1 every iterations through the loop. Let's go through that bit of code line by line:

[code]1) $url_array  = array()
2) for ($count = 0; $row = $results->Fetch_row(); ++count)
3) {
4)    $url_array[$count] = $row[0]
5) }[/code]

Line 1 simply creates an array variable called "$url_array". However it has no items in the array.

Line 2 creates a loop that 1. sets the value of $count to 0 and sets the exist condtiion for when "$row = $results->Fetch_row();" returns false (i.e. when there are no more records). The 3rd expression is what happens on each successive iteration of the loop - does not happen the first time through. So, the first iteration through the loop $count = 0, 2nd time $count = 1, etc.

Line 4 sets the value of $url_array[$count] to the value of the first item in the $row array. In other words, when the loop is complete:

$url_array[0] = the item from the 1st $row
$url_array[1] = the item from the 2nd $row
$url_array[2] = the item from the 3rd $row
.
.
.

Share this post


Link to post
Share on other sites
[quote author=mjdamato link=topic=113051.msg459667#msg459667 date=1162152969]
actually, $count starts at 0 and then inreases by 1 every iterations through the loop. Let's go through that bit of code line by line:

[code]1) $url_array  = array()
2) for ($count = 0; $row = $results->Fetch_row(); ++count)
3) {
4)    $url_array[$count] = $row[0]
5) }[/code]

Line 1 simply creates an array variable called "$url_array". However it has no items in the array.

Line 2 creates a loop that 1. sets the value of $count to 0 and sets the exist condtiion for when "$row = $results->Fetch_row();" returns false (i.e. when there are no more records). The 3rd expression is what happens on each successive iteration of the loop - does not happen the first time through. So, the first iteration through the loop $count = 0, 2nd time $count = 1, etc.

Line 4 sets the value of $url_array[$count] to the value of the first item in the $row array. In other words, when the loop is complete:

$url_array[0] = the item from the 1st $row
$url_array[1] = the item from the 2nd $row
$url_array[2] = the item from the 3rd $row
.
.
.

[/quote]

Wow thank you very much. :)  This was very helpful in helping me with the concept of what is going on in this loop.  I really appreciate you spending the extra time to get me up to speed. I know that was a lot of code I pasted. 

I can not say I am an expert on visualizing the many uses of arrays, but this has definitely help me a ton with one application.  For some reason arrays are a bit confusing to me as a whole. 

Hopefully I will start seeing all the uses soon so that as I just think about something and pragmatically see it visually. 

At least I feel I can move on in my book now that I have this concept understanding.

Thank you again!!!!


Share this post


Link to post
Share on other sites
I'd like to shove some more knowledge into your head if that's alright!

Just think of an array as a collection.  Every array is just collected data, nothing more and nothing less.  Usually we collect data in an array because it makes our lives as programmers easier!

For instance, would you rather create 100 variables named $book1, $book2, ..., $book100 or just a single array named $books and refer to them by $books[0], $books[1], ..., $books[99]?  What happens if you make a new variable for every book and have to perform the same operation on all of them?  You have to write that code 100 times!  If you use an array, you can loop over every element with for($i = 0; $i < 100; $i++){} or a foreach($books as $book){}!  That's a lot easier!

What if you have an application that processes employee data?  Would you rather call 10 different functions to get the data for an employee like this:
[code]<?php
$name = GetEmployeeName();
$add = GetEmployeeAddress();
$phone = GetEmployeePhone();
?>[/code]

Or would you rather call one function like this:
[code]<?php
$Employee = GetEmployee();
echo $Employee['Name'];
echo $Employee['Phone'];
?>[/code]

Whoah wait a minute there!  You just used text in the array!  That's right.  Up until now you've been using arrays and accessing them with integers.  Those values you use to access elements inside the array are what we call keys and they can be anything you want really.  Most of the time integers or strings will do fine though.

How about this array?
[code]<?php
$ShoppingCart = Array();
$ShoppingCart['Milk'] = Array( 'Brand' => 'Jed\'s Milk', 'Qty' => 2 );
$ShoppingCart['Cheese'] = Array( 'Brand' => 'Tillamook Pepper Jack', 'Qty' => 1 );
?>[/code]

From that array I know that my shopping cart consists of milk and cheese but not only that, I can see which brands and how much of each I have.  Just in case you didn't notice, $ShoppingCart is an array of arrays!

Good times!

Share this post


Link to post
Share on other sites
[quote author=roopurt18 link=topic=113051.msg460147#msg460147 date=1162237390]
I'd like to shove some more knowledge into your head if that's alright!

Just think of an array as a collection.  Every array is just collected data, nothing more and nothing less.  Usually we collect data in an array because it makes our lives as programmers easier!

For instance, would you rather create 100 variables named $book1, $book2, ..., $book100 or just a single array named $books and refer to them by $books[0], $books[1], ..., $books[99]?  What happens if you make a new variable for every book and have to perform the same operation on all of them?  You have to write that code 100 times!  If you use an array, you can loop over every element with for($i = 0; $i < 100; $i++){} or a foreach($books as $book){}!  That's a lot easier!

What if you have an application that processes employee data?  Would you rather call 10 different functions to get the data for an employee like this:
[code]<?php
$name = GetEmployeeName();
$add = GetEmployeeAddress();
$phone = GetEmployeePhone();
?>[/code]

Or would you rather call one function like this:
[code]<?php
$Employee = GetEmployee();
echo $Employee['Name'];
echo $Employee['Phone'];
?>[/code]

Whoah wait a minute there!  You just used text in the array!  That's right.  Up until now you've been using arrays and accessing them with integers.  Those values you use to access elements inside the array are what we call keys and they can be anything you want really.  Most of the time integers or strings will do fine though.

How about this array?
[code]<?php
$ShoppingCart = Array();
$ShoppingCart['Milk'] = Array( 'Brand' => 'Jed\'s Milk', 'Qty' => 2 );
$ShoppingCart['Cheese'] = Array( 'Brand' => 'Tillamook Pepper Jack', 'Qty' => 1 );
?>[/code]

From that array I know that my shopping cart consists of milk and cheese but not only that, I can see which brands and how much of each I have.  Just in case you didn't notice, $ShoppingCart is an array of arrays!

Good times!
[/quote]

Roopurt18, Thank you very much for the good overview.  It is very helpful for me getting the basic concept.  I appreciate you taking the time to be so detailed.

Thank you again!!!   

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.