How to include two or more, variables inside a function [ ex: foo( ); ]

Discussion in 'PHP' started by eritrea1, Oct 16, 2012.

  1. #1
    I have this function


    function foo($type){
    
    	if(isset($_GET['a_id']) && !empty($_GET['a_id'])){	
    			$page = $_GET['a_id'];
    			$query = "SELECT $type FROM d_articles WHERE a_id = '$page'";
    			$result = mysql_query($query);
    
    
    			while($row=mysql_fetch_array($result))
    			{ return " $row[$type]" ;}
    		} 
    Code (markup):
    In the above examples, I need to check 2 variables instead of one. i.e $type and $id, so How can I add that in the foo(); and inside the SELECT $type..


    And at last I need to echo it like
    <?php echo foo(); ?> 
    Code (markup):
    How do I include both varibles inside the foo
     
    eritrea1, Oct 16, 2012 IP
  2. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #2
    You would use:

    
    function foo($type, $id) {
    
        if (isset($_GET['a_id']) && !empty($_GET['a_id'])) {
            $page = $_GET['a_id'];
            $query = "SELECT $type FROM d_articles WHERE a_id = '$page'";
            $result = mysql_query($query);
    
    
            while ($row = mysql_fetch_array($result)) {
                return " $row[$type]";
            }
        }
    }
    
    PHP:
    You can access $id within the function as needed as long as you pass the parameter.

    This: <?php echo foo(); ?> would fail because you are not passing the type or id parameters to it.

    Here's a brief overview of passing and returning values from functions: http://www.php.net/manual/en/functions.arguments.php and http://www.php.net/manual/en/functions.returning-values.php
     
    jestep, Oct 16, 2012 IP
  3. ThePHPMaster

    ThePHPMaster Well-Known Member

    Messages:
    737
    Likes Received:
    52
    Best Answers:
    33
    Trophy Points:
    150
    #3
    I would suggest you also escape your variables you are using:

    
    function foo($type, $id) {
    
        if (isset($id) && isset($type)) {
            $query = "SELECT $type FROM d_articles WHERE a_id = '$id'";
            $result = mysql_query($query);
    
    
            while ($row = mysql_fetch_array($result)) {
                return $row[$type];
            }
        }
    }
    
    $type = mysql_real_escape_string($_GET['type']);
    $id = mysql_real_escape_string($_GET['id']);
    echo foo($type, $id);
    
    PHP:
     
    ThePHPMaster, Oct 17, 2012 IP
  4. php_developer

    php_developer Peon

    Messages:
    63
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    php_developer, Oct 20, 2012 IP