0

I need to display different verbiage according what the user's status is. I realize the while() variables are out of scope to Online_Status() but I cannot figure out how to share the variables or even define new variables in Online_Status() contianing the same information as while(). I've tried putting Online_Status() in while(), around while(), outside of while() and every other configuration for hours. Not happening. I would appreciate any help!

<?php

require_once('connect.php');


$con = mysqli_connect(DBHOST, DBUSER, DBPASS, DBNAME) or die('Connection failed: ' . mysqli_connect_error());

$sql = mysqli_query($con, "SELECT UserType, Online, InChat FROM membership WHERE UserType = 2 ORDER BY Online DESC");


    while($row = mysqli_fetch_array($sql)){

    $UserType = $row['UserType'];
    $Online = $row['Online'];
    $InChat = $row['InChat'];


    echo Online_Status(); 


    }

    function Online_Status(){ 

        if ($Online == 0) {
            echo "I am not online. Please come back later";
        }

        else if($Online == 1 && $InChat == 0){
            echo "I am Online and I will be in my chatroom shortly.";
        }

        else if($Online == 1 && $InChat == 1){
            echo "I am Online chat with me now!";
        }

}

mysqli_close($con);
?> 
Lori
  • 130
  • 12

1 Answers1

2

Use global keyword:

function Online_Status(){ 
    global $Online;
    if ($Online == 0) {
        echo "I am not online. Please come back later";
    }

}

It is better to pass variables through a function via function parameters:

function Online_Status($Online){ 
    if ($Online == 0) {
        echo "I am not online. Please come back later";
    }
}

And call it:

Online_Status($Online);

And also, take a look at PHP's Variable Scope.

Ali MasudianPour
  • 14,329
  • 3
  • 60
  • 62
  • 1
    It's generally seen as bad practice to use global variables but that's a matter of some contention and you're not going to be able to do much in PHP without learning to pass arguments into your methods, so I highly recommend using the second implementation that Ali is suggesting here – DaOgre Nov 12 '14 at 21:17
  • Exactly what I was looking for thank you. I was almost there, I'm sure I tried everything EXCEPT that. I'll try it out now. – Lori Nov 12 '14 at 23:05