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;
}
}
$resultSet -> fetch_all(MYSQLI_ASSOC);to get column names. By default, it returns a numeric array as you are seeing.