3

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.

9
  • your $userId is an object, how can you echo that ? What you want, please specify Commented Dec 16, 2016 at 12:20
  • Is $userId is an object of class user? Commented Dec 16, 2016 at 12:20
  • You need to return value from your function instead of echo. However your code doesn't make sense to get user_id and username ? For whom you are getting it ? do you want to get all user details ? Commented Dec 16, 2016 at 12:21
  • I would suggest you GOOGLE OOP and go through the docs. Commented Dec 16, 2016 at 12:21
  • the whole contruct of your class and how you use it is... hm.. unconventional. You need to read the docs again! Commented Dec 16, 2016 at 12:22

5 Answers 5

4

It doen't look like you've understood OOP just yet.

These code examples should hopefully give you an introduction but as in other comments, read up on OOP. I struggled with it at first but keep at it!

Create your user class
This class represents a single user and the actions associated with a user, think of it as a blue print. It should only perform functions related to a user, it shouldn't keed to 'know' about anything else. For example, database functions sholud be done elsewhere.

class User {
   private $id;
   private $name;

   function __construct($array)
   {
       $this->id = $array['id'];
       $this->name = $array['name'];
   }

   function getId()
   {
       return $this->id;
   }

   function getName()
   {
       return $this->name;
   }
}

Load all users into an array

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

$users = [];
while ($row = $result->fetch_assoc() ){
   $users[] = new User($row);
}

// this array now contains all your users as User objects
var_dump($users);

// echo all user's details
foreach($users as $user) {
   echo $user->getId();
   echo ' - ';
   echo $user->getName();
   echo "\r\n";
}

Load a single user

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

if ($row = $result->fetch_assoc()) {
   $user = new User($row);
} else {
   exit('User ID does not exist');
}

// echo the user's ID and name
echo $user->getId();
echo ' - ';
echo $user->getName();

Resourses
Laracasts - https://laracasts.com/series/object-oriented-bootcamp-in-php
Search PHP OOP explained - https://www.google.co.uk/search?q=php+oop+explained

Sign up to request clarification or add additional context in comments.

1 Comment

I really appreciate it Steve, and I am glad I am not the only one!
3
<?php

class user {

    // Get users ID
    function get_user_id() {

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

        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                $data[] = $row['id'] . ', ';
            }
        }
        return $data;
    }

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

        if ($result->num_rows > 0) {

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

$userId = new user;

$userName = new user;

// all user ids
$all_ids = $userId->get_user_id();

echo '<pre>';
print_r($all_ids);

// all user name 
$all_name = $userId->get_user_name();
echo '<pre>';
print_r($all_name);`enter code here`

Check first response from both function after use if condition

Comments

2

You are comparing object with 1 not the value returned by function get_user_id().

So instead of

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

Try

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

and then put in your condition

  if($id > 1){
     echo $name;
  } else {
  echo 'not working';
 }

I will suggest you to replace echo with return statement.

Comments

2

call your class as an object $userid = user(); $username = user();

you can also try something like this

class user
{

    // Get users ID
    function get_user_id($id = "")
    {
        global $conn;

        // check if id is empty or not
        if(!empty($id)) {
            $sql = 'SELECT id FROM users WHERE id = '.$id;
        }else{
            $sql = 'SELECT id FROM users';
        }
        $result = $conn->query($sql);

        if ($result->num_rows > 0) {

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

        }
    }

    // Get users name
    function get_user_name($name = "")
    {
        global $conn;

        // check if name is empty or not
        if(!empty($name)) {
            $sql = 'SELECT name FROM user WHERE name = '.$name;
        }else{
            $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();

    $userId->get_user_id(1);
    $userName->get_user_name();

    echo $userId;
    echo $userName;

please make sure you sanitize the id and name before use

Comments

0

IN both get_user_id, get_user_name methods please return $row = $result->fetch_assoc(); so, it will value comes in $userId, $userName and you can access it.

right now you return nothing so $user_id has null value so, it always goes in else condition.

Example

function get_user_id()
    {

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

        if ($result->num_rows > 0) {
            $value = '';

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

           return $value;
        }
    }

2 Comments

That isn't quire true, I do get my results back but not in the argument which is failing.
i think this one's help you check it again

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.