vendredi 16 décembre 2016

How to use php functions in IF statement

INTRO

I am trying to better understand my knowledge of Php and using classes to better prganise my code so this is just an exercise for a better understanding rather than a real world solution.

BRIEF

I am calling in a function from a class which I have just learnt to do but I want to know the best way to do something simple tasks like use the object in an IF statement.

SCENARIO

So for instance I am setting my classes like so:

    class user
    {

        // Get users ID
        function get_user_id()
        {

            global $conn;
            $sql = 'SELECT id FROM user';
            $result = $conn->query($sql);

            if ($result->num_rows > 0) {

                while ($row = $result->fetch_assoc() ){
                    echo $row['id'] . ', '; }

            }
        }

        // Get users name
        function get_user_name()
        {
            global $conn;
            $sql = 'SELECT name FROM user';
            $result = $conn->query($sql);

            if ($result->num_rows > 0) {

                while ($row = $result->fetch_assoc() ){
                    echo $row['name'] . ', ';   }

            }
        }

    }

$userId = new user;
$userName = new user;

I am then initializing in my classes like so:

<?php $userId->get_user_id(); ?>
<?php $userName->get_user_name(); ?>

and THEN I am wanting to performa simple task like show a user based on the value of their ID, the above will return 2 sets of results of 4 so id 1, 2, 3, 4 & Dan, Andy, Ryan, Aran

so I am performing a simple IF statement like so:

if($userId > 1){
    echo $userName;
} else {
    echo 'not working';
}

But it returns 'not working' - I am just wanting to better understand how to use the functions in a way that A works and B best practice.

Aucun commentaire:

Enregistrer un commentaire