PHP iterating through array returned from a function -
hi have class file contains function retrieve users mysql database. code following :
class userdbase { public function fetchusers() { $db = new mysqli('localhost', 'user', 'pass', 'dbase'); if($db->connect_errno > 0) { die('unable connect database [' . $db->connect_error . ']'); } $sql = "select username `users`"; if(!$result = $db->query($sql)) { die('there error running query [' . $db->error . ']'); } while($row = $result->fetch_assoc()) { $users[] = $row['username']; } $result->free(); $db->close(); return array($users); } }
the code above returns array following using print_r($dbase->fetchusers()) :
array ( [0] => array ( [0] => user1 [1] => user2 [2] => user3 ) )
i having trouble looping through array main file reference function in class . code using following :
<?php require("dbase.php"); $dbase = new userdbase(); foreach($dbase->fetchusers() $result) //this doesn't work { print "$result"; } ?>
can more versed in php point me out correct way ? in advance !
when build array of users[] here:
while($row = $result->fetch_assoc()) { $users[] = $row['username']; }
$users array, when return it, wrapping in array() means returning array of arrays not process.
solution return $users.
Comments
Post a Comment