Jump to content

Call a variable inside a function?


houston08

Recommended Posts

Hello! I have a quick question about calling a variable inside a function.

 

<?PHP

function inside() {
$a = "Test Works";
$b = 1;
}

if ($b=="1") {

echo $a;

}else{

echo "Test Failed";

};

?>

 

As you can see I want to get the value of $a but I cannot.

 

Below is code in question that I'm working with:

 

function index($user) {
     global $db, $prefix;

     //check if the user is logged in or not.
     if (is_logged_in($user)) {
          include("header.php");

          $cookie_read = explode("|", base64_decode($user));
          //define variables to hold cookie values.
	  $userid = $cookie_read[0];

 

I want to get the $userid outside of the function, who would I do that?

Link to comment
Share on other sites

EDITED READ AGIN PLEASE >>>>>

 

you ended the function at the start of the code .

 

example 1

<?php

function inside() {

$a = "Test Works";
$b = 1;


if ($b=="1") {

echo $a;

}else{

echo "Test Failed";

};
}
echo inside();

?>

 

 

do you mean this mate?

 

example 2.

<?php

function inside() {

global $a;
global $b;

$a = "Test Works";
$b = 1;

}

inside();

if ($b=="1") {

echo $a;

}else{

echo "Test Failed";

};



?>

Link to comment
Share on other sites

try this please.

<?php
function index($user) {
     global $db, $prefix;

     //check if the user is logged in or not.
     if (is_logged_in($user)) {
          include("header.php");

          $cookie_read = explode("|", base64_decode($user));
          //define variables to hold cookie values.
        
          global $userid;
          
          $userid = $cookie_read[0];
     }

}


index($user);

echo $userid;

?>

Link to comment
Share on other sites

can you please clarify what you by returning the value?

 

function index($user) 
{
   global $db, $prefix; //<-- I don't like globals here, either

   //check if the user is logged in or not.
   if (is_logged_in($user))
   {
      include("header.php");

      $cookie_read = explode("|", base64_decode($user));
      //define variables to hold cookie values.
          
      $userid = $cookie_read[0];
   }

   return $userid;
}


$userId = index($user);

 

Functions can return values/results to the code that invoked them.  Simply assign the function invocation to a variable to capture the return value.

Link to comment
Share on other sites

Ok, sorry for the mixup. I think I need to further clarify what I'm wanting to do.

 

Below is the main page in index.php

The Header.php and Footer.php files contain the html wrapping around the PHP code. (you'll see i still need improvement in some ways but I'm learning.  ;) )

 

<?PHP
include ("functions.php");

// the Default function.
//note for functions: if you want to include a value of some variables inside the funtions,
//then you have to GLOBAL it first.
function index($user) {
     global $db, $prefix;

     //check if the user is logged in or not.
     if (is_logged_in($user)) {
          include("header.php");

          $cookie_read = explode("|", base64_decode($user));
          //define variables to hold cookie values.
        
          global $userid;
          
          $userid = $cookie_read[0];
          $username = $cookie_read[1];
          $password = $cookie_read[2];
          $ipaddress = $cookie_read[3];
          $lastlogin_date = $cookie_read[4];
          $lastlogin_time = $cookie_read[5];
          if($ipaddress == "") $ipaddress = ""._NOT_YET."";
         
	  
          //print wilcome message
          echo "<h3>"._WELCOME." <b>$username</b>!</h3>";
	  echo "<p>Here are the most recent additions to the public listings:</p>";		  
	  
	  $searchstring = "WHERE `account` != '0'";
	  $table = "listings";
	  $order = "1";
	  $pagination = pagination($table, $order, $searchstring, $pre, $pos, $nav, $page, $pages);
	  $navigation = $pagination[0];
	  $result = $pagination[1];
	  $num = $pagination[2];
	  // echo"$navigation";
	  
	  echo "<table class=\"hover\">";
	  echo "<tr>";
	  echo "<th>Contact</th><th>Last Years Percent</th><th>Location</th><th>Amount</th></tr>";
	  
	  for($i; $i < mysql_num_rows($result); $i++)
	  {
	  $row = mysql_fetch_array($result);
	  echo ($i % 2 == 0) ? '<tr>' : '<tr class="altrow">' . "\n"; 
	  echo "<td>"; echo $row['ContactFirst']; echo " "; echo $row['ContactLast']; echo "</td>";
	  echo "<td>"; echo $row['LastYearsPercent']; echo "</td>";
	  echo "<td>"; echo $row['City']; echo ", "; echo $row['State']; echo "</td>";
	  echo "<td>"; echo $row['Amount']; echo "</td>";
	  }  
	  
	  echo "</table>";
          navigation_menu();
          include("footer.php");		  
     }else{
         //if the user is not logged in then show the login form.
         //  header("Location: users.php?a=Login");  die();
         include("header.php");
         $login_needed = 1;
         include("footer.php");
    }

}

index($user);
?>

 

Now I want to take the value from $userid; and put it into this function that will insert it into the database:

 

function do_AddListing(){

             include("header.php");
		 $ContactFirst = $_POST['ContactFirst'];
		 $ContactLast = $_POST['ContactLast'];
		 $Email = $_POST['Email'];
		 $Phone = $_POST['Phone'];
		 $Comments = $_POST['Comments'];
		 mysql_connect("localhost", "root", "") or die(mysql_error());
		 mysql_select_db("oillisting") or die(mysql_error());
		 mysql_query("INSERT INTO `listings` VALUES ('', '$userid', '$ContactFirst', '$ContactLast', '$Email', '$Phone', '$Comments')") or die("No Worky");
		 echo "Success!";
             include("footer.php");
}

 

So using the code of

 

index($user);

echo $userid;

 

Isn't good because it calls another entire page. What else can I do or would anyone suggest some modifications to my code? Thanks! Yall have been a great help already!

Link to comment
Share on other sites

Your function is kind of complex, consider breaking it up into smaller functions which may allow you to pull $userid without extracting an entire page in the process.

i.e., you made a separate function that sets and returns $userid, insert that into function index() and also insert it into doAddlisting()

Link to comment
Share on other sites

Your function is kind of complex, consider breaking it up into smaller functions which may allow you to pull $userid without extracting an entire page in the process.

i.e., you made a separate function that sets and returns $userid, insert that into function index() and also insert it into doAddlisting()

 

Exactly.  Also, I abhor using globals of any kind.  They make code harder to debug and modify.  There's a reason why functions can take arguments and return values, and there's a reason why PHP and virtually all other modern programming languages you're likely to encounter have references.  So when I see something like:

 

//note for functions: if you want to include a value of some variables inside the funtions,
//then you have to GLOBAL it first.

 

I cringe.

Link to comment
Share on other sites

Well from what I have been reading, and obviously with yalls opinions, globals are usually not good. The login script is not my own though, so at least I can't take the blame fully for that, but it does lead me to believe I should find another one, if not attempt to make my own... which would take lots of work.

 

I did split the function, even if just a little bit. I made the cookie read it's own function.

include ("functions.php");

// the Default function.
//note for functions: if you want to include a value of some variables inside the funtions,
//then you have to GLOBAL it first.
function cookied() {
          $cookie_read = explode("|", base64_decode($user));
          //define variables to hold cookie values.
          
	  global $userid;
	  
          $userid = $cookie_read[0];
          $username = $cookie_read[1];
          $password = $cookie_read[2];
          $ipaddress = $cookie_read[3];
          $lastlogin_date = $cookie_read[4];
          $lastlogin_time = $cookie_read[5];


}

function index($user) {
     global $db, $prefix;

	cookied();

     //check if the user is logged in or not.
     if (is_logged_in($user)) {
          include("header.php");

	  //print wilcome message
          echo "<h3>"._WELCOME." <b>$username</b>!</h3>";
	  echo "<p>Here are the most recent additions to the public listings:</p>";		  
	  
	  $searchstring = "WHERE `account` != '0'";
	  $table = "listings";
	  $order = "1";
	  $pagination = pagination($table, $order, $searchstring, $pre, $pos, $nav, $page, $pages);
	  $navigation = $pagination[0];
	  $result = $pagination[1];
	  $num = $pagination[2];
	  // echo"$navigation";
	  
	  echo "<table class=\"hover\">";
	  echo "<tr>";
	  echo "<th>Contact</th><th>Last Years Earnings</th><th>Location</th><th>Amount</th></tr>";
	  
	  for($i; $i < mysql_num_rows($result); $i++)
	  {
	  $row = mysql_fetch_array($result);
	  echo ($i % 2 == 0) ? '<tr>' : '<tr class="altrow">' . "\n"; 
	  echo "<td>"; echo $row['ContactFirst']; echo " "; echo $row['ContactLast']; echo "</td>";
	  echo "<td>"; echo $row['LastYearsEarnings']; echo "</td>";
	  echo "<td>"; echo $row['City']; echo ", "; echo $row['State']; echo "</td>";
	  echo "<td>"; echo $row['Amount']; echo "</td>";
	  }  
	  
	  echo "</table>";
          navigation_menu();
          include("footer.php");
     }else{
         //if the user is not logged in then show the login form.
         //  header("Location: users.php?a=Login");  die();
         include("header.php");
         $login_needed = 1;
         include("footer.php");
    }

}

 

I'm open to really anything though. All the suggestions and feedback I'm learning from, and really appreciate it.

Link to comment
Share on other sites

Well, right now, your cookieid() function won't work because you don't pass $user into it.  And, once again, you don't return any values.  And I thought that your script came from a 3rd party...the code had that funky 'smell' to it.

 

What you should do is brush up on/learn basic PHP.  Functions (arguments and return values) and scope would be a good place to start.

 

As to your functions, here's a quick sketch of how I'd modify it without completely rewriting everything from the ground-up:

 

include ("functions.php");

function readCookie($user)
{
   $cookieData = explode("|", base64_decode($user));

   return $cookieData
}

function index($user)
{
   global $db, $prefix; // <-- Keeping these only because the system depends on them.

   $cookieInfo = readCookie($user);

   include("header.php");

   //check if the user is logged in or not.
   if (is_logged_in($user))
   {
      //print welcome message
      echo "<h3>WELCOME<b>" . $cookieInfo[0] . "</b>!</h3>";
      echo "<p>Here are the most recent additions to the public listings:</p>";
      
      $searchstring = "WHERE `account` != '0'";
      $table = "listings";
      $order = "1";
      $pagination = pagination($table, $order, $searchstring, $pre, $pos, $nav, $page, $pages);

      $navigation = $pagination[0];
      $result = $pagination[1];
      $num = $pagination[2];

      echo "<table class=\"hover\"><tr>";
      echo "<th>Contact</th><th>Last Years Earnings</th><th>Location</th><th>Amount</th></tr>";

      for($i; $i < mysql_num_rows($result); $i++)
      {
         $row = mysql_fetch_array($result);
         echo ($i % 2 == 0) ? '<tr>' : '<tr class="altrow">' . "\n"; 
         echo "<td>" . $row['ContactFirst'] . " " . $row['ContactLast'] . "</td>";
         echo "<td>" . $row['LastYearsEarnings'] . "</td>";
         echo "<td>" . $row['City'] . ", " . $row['State'] . "</td>";
         echo "<td>" . $row['Amount'] . "</td>";
      }  

      echo "</table>";

      navigation_menu();
   }
   else
   {
      $login_needed = 1;
   }

   include("footer.php");
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.