paulcruse3
paulcruse3

Reputation: 189

PHP Loops to Functions

I understand looping through MySQL tables with for loops and extracting out data via if statements (among other things).

But now I am trying to better understand functions. So to keep it simple and a point of reference I understand, this is what I am used to doing:

require 'get_member_email.php'//where $memberEmail is defined
$query = "SELECT * FROM TABLE WHERE SOMETHING='SOMETHING ELSE'";
$results = mysql_query($query);

foreach ($results as $data){
      if ($memberEmail == $data['member_email']{ 
             $id = $data['member_id'];
      }
}

I would normally store that script in a file then call into my website with a require (as well as the file 'above' it (where $memberEmail is defined), then call both files into my webpage via:

require 'get_member_email.php';// where $member email is defined
require 'get_memeber_id.php'; //where the code above is 
echo "<h1>Your member ID is: $id</h1>";

1) How would I write this functions 2) Is there any benefit to doing so? (rather than just keeping my require and for loops)

Upvotes: 1

Views: 92

Answers (2)

Gian Carlo
Gian Carlo

Reputation: 215

1) Okay your question is how to write a function.

function loopFunction() {
    require 'get_member_email.php';
    $query = "SELECT * FROM TABLE WHERE SOMETHING='SOMETHING ELSE'";
    $results = mysql_query($query);

    foreach ($results as $data) {
        if ($memberEmail == $data['member_email']{ 
         $id = $data['member_id'];
        }
    }
}

by doing this you can store this process and simply call it by

loopFunction();

2) Yes there is a benefit of doing this. since you already define this as a function you dont have to create this process again. you can just call it.

This benefits you when this process needs to be repeated or re used in other cases.

Upvotes: 1

DACrosby
DACrosby

Reputation: 11440

You grab all of the data of a single member in your database call already.

require 'get_member_email.php'; // Define $memberEmail

// Select the member's data from the database
$query = "SELECT * FROM TABLE WHERE member_email = '".$memberEmail."'";

// Only need one member's data, so grab it.
$results = mysql_fetch_array($query);

$id = $results['id'];

Note: mysql queries are depreciated in newer versions of PHP; use mysqli calls instead.

Upvotes: 1

Related Questions