0

I am working on converting a procedural php code to mysqli OOP the code below returns all users based on joined information

   public static function find_all_users()
    {
        $db = getConn();

        $stmt = $db->prepare("
         SELECT * 
         FROM users 
         JOIN roles 
         WHERE roles.role_id = users.role_id 
         ORDER BY created_at");

        $stmt->execute();
        $user = $stmt->get_result();
        $stmt->close();

        return $user->fetch_object();
    }

When I do a var_dump it gives me and object, however on the page to display it i call

$users = User::find_all_users();

Then

<?php if (!empty($users)) : ?>

    <ul>
    <?php foreach ($users as $user) : ?>
            <li>
                <div>
                    <h2><?= $user['name'] ?></a></h2>
                    <p><?= $user['email'] ?></p>
                </div>
            </li>
    <?php endforeach; ?>
    </ul>

<?php else : ?>

    <p>No User found.</p>

<?php endif; ?>

If i try to use $this->id or $user->id it tells me I am trying to get a non object but when I var_dump $users it returns a object?

object(stdClass)[5]
  public 'id' => int 1
  public 'name' => string 'bigjah' (length=4)
  public 'email' => string '[email protected]' (length=22)
  public 'password' => string '$2y$10$TOPc3JHjtoxfJQI14EMRj.ybVkgEPo4KB6.yB5s6pK/PHWO1GOaDy' (length=60)
  public 'created_at' => string '2021-09-25 01:32:38' (length=19)
  public 'about' => null
  public 'ip_address' => string '127.0.0.1' (length=9)
  public 'reset_token' => null
  public 'reset_key' => null
  public 'confirmed' => string '857795025069' (length=12)
  public 'verified' => int 0
  public 'role_id' => int 4
  public 'role_title' => string 'Administrator' (length=13)
5
  • 4
    fetch_object returns a single object from the current row. You probably want fetch_all or fetch_array
    – Chris Haas
    Oct 7, 2021 at 3:30
  • @ChrisHaas if i do that then I cannot use $this->id or $user->id only $user['id'] is that not bad in OOP?
    – Method
    Oct 7, 2021 at 3:36
  • 2
    OOP is a programming paradigm. What matters is whether code works or doesn’t work. Your functions name implies that it returns a collection (array) of something. Whether that “something” is an object or a sub array doesn’t really matter. Don’t force OOP onto something, use it if/when it makes sense to you.
    – Chris Haas
    Oct 7, 2021 at 3:39
  • @ChrisHaas thank you I am new to OOP I had lots of questions but no answers so it dont matter if it uses $this-> if i used an array and used $row['id'] it would still be clean
    – Method
    Oct 7, 2021 at 3:41
  • 2
    $this is used when you are inside of a class. When you are outside, $this no longer exists. OOP is not faster, better, cleaner, etc., those are just opinions by people. If you don’t get OOP, don’t use it. That said, there’s a trend towards it so I’d look for a good and thorough tutorial on it.
    – Chris Haas
    Oct 7, 2021 at 3:46

2 Answers 2

0

First of all, I have to point out that this would be easier if you were using PDO instead of mysqli. I highly recommend considering an upgrade.

The reason why it doesn't work for you is that User::find_all_users(); returns a single object, not an array of objects. This means that you return only a single user.

If you would like to return an array of objects (each one representing a single user) you can collect them into an array like this:

public static function find_all_users(): array
{
    $db = getConn();
    
    $stmt = $db->prepare("
        SELECT * 
        FROM users 
        JOIN roles 
        WHERE roles.role_id = users.role_id 
        ORDER BY created_at");
    
    $stmt->execute();
    $results = $stmt->get_result();
    
    // populate the array with users
    $return_array = [];
    while($user = $results->fetch_object()) {
        $return_array[] = $user;
    }

    return $return_array;
}
    <?php foreach (User::find_all_users() as $user) : ?>
            <li>
                <div>
                    <h2><?= $user->name ?></a></h2>
                    <p><?= $user->email ?></p>
                </div>
            </li>
    <?php endforeach; ?>

If you would like to return just an array of arrays (which is simpler if you are not using PDO) then you can simply call fetch_all():

public static function find_all_users(): array
{
    $db = getConn();
    
    $stmt = $db->prepare("
        SELECT * 
        FROM users 
        JOIN roles 
        WHERE roles.role_id = users.role_id 
        ORDER BY created_at");
    
    $stmt->execute();
    $results = $stmt->get_result();

    // return all rows as associative arrays
    return $results->fetch_all(MYSQLI_ASSOC);
}
    <?php foreach (User::find_all_users() as $user) : ?>
            <li>
                <div>
                    <h2><?= $user['name'] ?></a></h2>
                    <p><?= $user['email'] ?></p>
                </div>
            </li>
    <?php endforeach; ?>
0

You are iterating over a single object, if that dump is the result of dumping $usrs. Therefore, change the way you fetch the statement into $st->fetchAll(PDO::FETCH_CLASS); if you are using PDO. But I see that you are not so $user -> fetch_all(MYSQLI_ASSOC);

To use the result of your query as an object

while ($user = find_all_users()): ?>
     <h2><?= $user->name ?></a></h2>
}

That means you loop every time you get an instance of the object from your current function.

3
  • You were on the right track with this answer, but the while loop does not look right. $user will be a multidimensional array and it will only iterate once. You'd have to use foreach, which OP is using so I have no idea why you changed it to while
    – Dharman
    Oct 7, 2021 at 12:38
  • Yes, that was my first suggestion. But OP implied he didn't want the associative array but an oop approach. Hence, I thought he can keep his function, which returns one instance of an object every time it is called.
    – altsyset
    Oct 7, 2021 at 20:22
  • Yeah, that is not going to work. Try it yourself. This will always show the same user record.
    – Dharman
    Oct 7, 2021 at 20:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.