Jump to content

PHP function - Undefined Variable


Adamhumbug

Recommended Posts

Hi All,

I have been trying to condilidate my code into a functions file so that i can call bits of code.

I have a page that populates some buttons, using data from a DB, it decides what buttons to show based on information in the URL.

The issue that i was having was that until they press another button, there is not the required information in the URL to be used in the SQL.

To combat this i wrote a bit of code (the bit that is now not working)

 if (strpos($_SERVER['REQUEST_URI'], "product") == false){
            $product_cat = $setFirstArray;
          }else{
            $product_cat = urldecode($_GET['product_catagory']);
          }

This was working but i now appear to have broken it by moving me code into functions.

The error that i am getting is Notice: Undefined variable: setFirstArray in /homepages/29/d742272110/htdocs/home.php on line 20

This is the second line of the code above.

function showSideBarProductButtons($conn){


  $sql = "SELECT DISTINCT product_catagory FROM pos_pr GROUP BY product_catagory ORDER BY product_catagory ASC";

  if($result = mysqli_query($conn, $sql)){
    if(mysqli_num_rows($result) > 0){
  $firstarray = array();

      while($row = mysqli_fetch_array($result)){
        echo "<a href=home.php?product_catagory=" . urlencode($row['product_catagory']) ."><div class='col-md-12 btn btn-primary tb-space'>" . $row['product_catagory'] . "</div></a>";

      //below - $prods becomes every product one at a time as it is in while
        $prods =$row['product_catagory'];
      //below - adds value of $prods to array called $firstarray one at a time until end
        array_push($firstarray,$prods);
      }
      mysqli_free_result($result);

    }else{
      echo "This did not work!";
    }
    //below - spits out first value of array
  $setFirstArray=$firstarray[0];
  echo $setFirstArray;
  
  }
}

The above is the function that creates the side buttons.  It also sets the varaible $setFirstArray to be the first value in the array - this works and the echo at the end confirms this.

What is not working (the code mentioned above) says that the variable $setFirstArray is not defined.

 

<div class="col-md-7 border">
          <?php

          

          if (strpos($_SERVER['REQUEST_URI'], "product") == false){
            $product_cat = $setFirstArray;
          }else{
            $product_cat = urldecode($_GET['product_catagory']);
          }


          //this is looking at functions.php and running the code from there
          getProductMainButtons($conn, $product_cat);
           ?>


        </div>

Above is the code for this section in full.

 

Any help or pointers on this would be apprecitaed.

Edited by Adamhumbug
Spelling
Link to comment
Share on other sites

Variables created within a function are available only within that function.

http://php.net/manual/en/language.variables.scope.php

You could return the variable from the function. EG

function showSideBarProductButtons($conn){
    
    ...
    
    $firstArray = array();
    
    ...
    
    return $firstArray;
}

$setFirstArray = showSideBarProductButtons($conn);

 

Link to comment
Share on other sites

Hi,

Thanks so much for your reply.

What you suggested worked for the most part - there is obviously something i am missing here.

I now have the following function

function showSideBarProductButtons($conn){


  $sql = "SELECT DISTINCT product_catagory FROM pos_pr GROUP BY product_catagory ORDER BY product_catagory ASC";

  if($result = mysqli_query($conn, $sql)){
    if(mysqli_num_rows($result) > 0){
  $firstarray = array();

      while($row = mysqli_fetch_array($result)){
        echo "<a href=home.php?product_catagory=" . urlencode($row['product_catagory']) ."><div class='col-md-12 btn btn-primary tb-space'>" . $row['product_catagory'] . "</div></a>";

      //below - $prods becomes every product one at a time as it is in while
        $prods =$row['product_catagory'];
      //below - adds value of $prods to array called $firstarray one at a time until end
        array_push($firstarray,$prods);
      }
      mysqli_free_result($result);

    }else{
      echo "This did not work!";
    }
    //below - spits out first value of array



  }
    return $firstarray[0];
}

And the following home page

<div class="col-md-7 border">
          <?php

$setFirstArray = showSideBarProductButtons($conn);

          if (strpos($_SERVER['REQUEST_URI'], "product") == false){
            $product_cat = $setFirstArray;
          }else{
            $product_cat = urldecode($_GET['product_catagory']);
          }


          //this is looking at functions.php and running the code from there
          getProductMainButtons($conn, $product_cat);
           ?>


        </div>

The issue is that the sidebar buttons now appear in the main section. 

I am assuming that i have put something in the wrong place?

 

Thanks again

Kind Regards

 

Link to comment
Share on other sites

13 minutes ago, Adamhumbug said:

I am assuming that i have put something in the wrong place?

It looks that way.

This line will be output wherever you call the function:

echo "<a href=home.php?product_catagory=" . urlencode($row['product_catagory']) ."><div class='col-md-12 btn btn-primary tb-space'>" . $row['product_catagory'] . "</div></a>";

It might be better if your function were to just populate the array and return it. Having got the data, then output it where required.

 

BTW, this part of your query is totally redundant - you are already using SELECT DISTINCT.

GROUP BY product_catagory
Link to comment
Share on other sites

Ok, thanks guys for the pointers.

So i have returned the first value of the array

$firstProd = $firstarray[0];
    return $firstProd;

Then i have writted a second function

function useFirstProdValue(){
  echo $firstProd;
}

i still get undefined variable so i am assuming that there is a step i need to take to get the variable into my new function.

I have tried adding $firstProd into the () but this gives me a fatal.

The google resuklts are not all too clear when looking at this.

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.