0

I made a function in order to get all users from my database $allUsers = selectAllUsers($conn);

This function is working well and var_dump give me an array like this

array(49) { [0]=> array(4) { [0]=> int(1) [1]=> string(15) "Thomas Anderson" [2]=> string(16) "[email protected]" [3]=> string(4) "Thom" } [1]=> array(4) { [0]=> int(2)

Now I made a foreach loop which is working well in order to display the data like this

<?php
  var_dump(selectAllUsers($conn));
  $allUsers = selectAllUsers($conn);
  if ($allUsers) {
   $i = 0;
   foreach ($allUsers as $key) {
    $i++;
?>
    <tr>
        <td><?php echo $key[0] ?></td>
        <td><?php echo $key[1] ?></td>
        <td><?php echo $key[2] ?></td>
        <td><?php echo $key[3] ?></td>
    </tr>
<?php
   }
  }
?>

My fields from users database are: users_id, users_name, users_email, users_uid

But I want something like this in order to name the fields. Unfortunately I got an error from php "Undefined index: users_id in"

foreach ($allUsers as $key) {
    $i++;
    <tr>
        <td><?php echo $key["users_id"] ?></td>
        <td><?php echo $key["users_name"] ?></td>
        <td><?php echo $key["users_uid"] ?></td>
        <td><?php echo $key["users_email"] ?></td>
    </tr>
<?php

How can I manage that?

Here my function:

function selectAllUsers($conn)
{
    $sql = "SELECT users_id, users_name, users_email, users_uid FROM users ORDER BY users_id ASC;";
    $stmt = $conn->prepare($sql);
    $stmt->execute();
    $resultSet = $stmt->get_result();
    $result = $resultSet->fetch_all();
    if ($result) {
        return $result;
    }
}
2
  • 2
    You should start by fetching the data from the result set as an associative array then, instead of a numerically indexed one. Commented Oct 27, 2020 at 12:56
  • 1
    Yes, use $resultSet -> fetch_all(MYSQLI_ASSOC); to get column names. By default, it returns a numeric array as you are seeing. Commented Oct 27, 2020 at 13:01

1 Answer 1

2

If you want to use associative keys then you need to fetch associative array from mysqli_result. Use this:

$resultSet->fetch_all(MYSQLI_ASSOC);

If you want to have both numerical and associative keys then you can use:

$resultSet->fetch_all(MYSQLI_BOTH);

Also, I would like to point out that your if statement in that function is not very useful. You can remove it. Your function can then become:

function selectAllUsers($conn)
{
    $sql = "SELECT users_id, users_name, users_email, users_uid FROM users ORDER BY users_id ASC;";
    $stmt = $conn->prepare($sql);
    $stmt->execute();
    return $stmt->get_result()->fetch_all(MYSQLI_BOTH);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.