This question already has answers here:
return inside foreach php and laravel
(2 answers)
Closed 3 years ago.
Im fairly new to OOP way of coding and I want to fetch a record of users in my DB
This is my code below:
$con = new mysqli('localhost', 'root', '', 'goldpalace');
class User {
public $connect;
public function get_users() {
$sql = "SELECT * from users";
$result = $this->connect->query($sql);
$num_rows = $result->num_rows;
if ($num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$data[] = $row;
return $data;
}
}
}
}
$obj = new User();
$obj->connect = $con;
$user_data = $obj->get_users();
foreach ($user_data as $value) {
echo $value['name']."<br>";
}
I have a lot of records in my DB but it only returns the first row.
That's because you return the value of $data immediately after you retrieve one row. return will return that value and stop execution of that method. You need to return that value after you are done retrieving your values.
class User {
public $connect;
public function get_users() {
$sql = "SELECT * from users";
$result = $this->connect->query($sql);
$num_rows = $result->num_rows;
$data = [];
if ($num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
return $data;
}
}
FYI, you can use fetch_all() here to make this a bit simpler:
class User {
public $connect;
public function get_users() {
$sql = "SELECT * from users";
$result = $this->connect->query($sql);
$num_rows = $result->num_rows;
$data = [];
if ($num_rows > 0) {
$data = $result->fetch_all(MYSQLI_ASSOC);
}
return $data;
}
}
For you return in the first cycle in while
while ($row = $result->fetch_assoc()) {
$data[] = $row;
return $data;
}
just move the return out of while loop
while ($row = $result->fetch_assoc()) {
$data[] = $row;
}
return $data;
Related
hi i"ve created multiples tables in sql first time s i'm having difficulties in fetching data. so here is my code ,
<?php
// Use to fetch product data
class Product
{
public $db = null;
public function __construct(DBController $db)
{
if (!isset($db->con)) return null;
$this->db = $db;
}
// fetch product data using getData Method
public function getData($table = 'lipstick', $liner = 'liner', $brush = 'brush', $eyeshadow = 'eyeshadow'){
$result = $this->db->con->query( "SELECT * FROM {$table}");
$result1 = $this->db->con->query( "SELECT * FROM {$liner}");
$result2 = $this->db->con->query("SELECT * FROM {$eyeshadow}");
$result3 = $this->db->con->query("SELECT * FROM {$brush}");
$resultArray = array();
// fetch product data one by one
while ($item = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$resultArray[] = $item;
}
return $resultArray;
}
i'm only getting data from $result as i want to fetch data from $result 1-3.
i tried to run loop for all the result variables like this,
<?php
// Use to fetch product data
class Product
{
public $db = null;
public function __construct(DBController $db)
{
if (!isset($db->con)) return null;
$this->db = $db;
}
// fetch product data using getData Method
public function getData($table = 'lipstick', $liner = 'liner', $brush = 'brush', $eyeshadow = 'eyeshadow'){
$result = $this->db->con->query( "SELECT * FROM {$table}");
$result1 = $this->db->con->query( "SELECT * FROM {$liner}");
$result2 = $this->db->con->query("SELECT * FROM {$eyeshadow}");
$result3 = $this->db->con->query("SELECT * FROM {$brush}");
$resultArray = array();
// fetch product data one by one
while ($item = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$resultArray[] = $item;
}
return $resultArray;
// fetch product data one by one
while ($item1 = mysqli_fetch_array($result1, MYSQLI_ASSOC)){
$resultArray[] = $item1;
}
return $resultArray;
// fetch product data one by one
while ($item2 = mysqli_fetch_array($result2, MYSQLI_ASSOC)){
$resultArray[] = $item2;
}
return $resultArray;
// fetch product data one by one
while ($item3 = mysqli_fetch_array($result3, MYSQLI_ASSOC)){
$resultArray[] = $item3;
}
return $resultArray;
}
but i got the error which was ::undefined variable item1-3 in line no 74::
what should i do now.
You have some mistakes in your code, i somekind of "corrected" your code for you.
return statement exits your function means code below return is not executed
you can reuse variables
use multidimensional array to store multiple tables in one array
I know its not the best way to query the database - but i hope it helps you a little
public function getData($table = 'lipstick', $liner = 'liner', $brush = 'brush', $eyeshadow = 'eyeshadow'){
$result = $this->db->con->query( "SELECT * FROM {$table}");
$result1 = $this->db->con->query( "SELECT * FROM {$liner}");
$result2 = $this->db->con->query("SELECT * FROM {$eyeshadow}");
$result3 = $this->db->con->query("SELECT * FROM {$brush}");
$resultArray = array();
// fetch product data one by one
$resultArray[$table] = array();
while ($item = mysqli_fetch_array($result, MYSQLI_ASSOC)){
array_push($resultArray[$table], $item);
}
//return $resultArray; //no return here, if you return here the code below will not be executed
// fetch product data one by one
$resultArray[$liner] = array();
while ($item = mysqli_fetch_array($result1, MYSQLI_ASSOC)){
array_push($resultArray[$liner], $item);
}
//return $resultArray; //no return here, if you return here the code below will not be executed
// fetch product data one by one
$resultArray[$eyeshadow] = array();
while ($item = mysqli_fetch_array($result2, MYSQLI_ASSOC)){
array_push($resultArray[$eyeshadow], $item);
}
//return $resultArray; //no return here, if you return here the code below will not be executed
// fetch product data one by one
$resultArray[$brush] = array();
while ($item = mysqli_fetch_array($result3, MYSQLI_ASSOC)){ //you can reuse $item
array_push($resultArray[$brush], $item);
}
return $resultArray;
}
I am fetching data from MYSQL database and Looping through the result but its returning only one row !!! can any one explain what's wrong
function getAll()
{
global $con;
$SQL = "SELECT * FROM users";
$stmt = $con->query($SQL);
if($stmt->num_rows > 0){
while($row = $stmt->fetch_row())
{
return $row;
}
}
}
The return should be outside the while loop !
Here is how you can get all the rows :
function getAll()
{
global $con;
$SQL = "SELECT * FROM users";
$stmt = $con->query($SQL);
if($stmt->num_rows > 0){
$arr = array();
while($row = $stmt->fetch_row())
{
$arr[] = $row;
}
return $arr;
}
}
Or you can do something like this return a generator and loop through :
function getAll()
{
global $con;
$SQL = "SELECT * FROM users";
$stmt = $con->query($SQL);
if($stmt->num_rows > 0){
while($row = $stmt->fetch_row())
{
yield $row;
}
}
}
see the result here !
echo '<pre>';
foreach (getAll() as $value) {
print_r($value);
}
Once you hit a return statement all execution of that function stops. You cannot return multiple times.
You can either return an array of all rows:
function getAll()
{
global $con;
$SQL = "SELECT * FROM users";
$stmt = $con->query($SQL);
if($stmt->num_rows > 0) {
while($row = $stmt->fetch_row())
{
$array[] = $row;
}
return $array;
}
}
Or use it as a generator (probably not what you want):
function getAll()
{
global $con;
$SQL = "SELECT * FROM users";
$stmt = $con->query($SQL);
if($stmt->num_rows > 0){
while($row = $stmt->fetch_row())
{
yield $row;
}
}
}
I have a getData() function, and a database with two tables: employers and members.
I would like to pass a variable containing the table name, so inside an "if" I could execute the appropriate SELECT statement. My problem I believe that after the "if" the $stmt->bind_param(); doesn't know which $stmt to bind the take.
Any ideas on how I could achieve this?
Thanks
public function getData($table)
{
if ($table == "employers")
{
$stmt = $this->link->prepare("SELECT * FROM employers ");
}
else
{
$stmt = $this->link->prepare("SELECT * FROM members ");
}
$stmt->bind_param();
if ($stmt->execute())
{
$result = $stmt->get_result();
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
$row = array_map('stripslashes', $row);
$dataArray[] = $row;
}
}
return $dataArray;
}
No, since you aren't binding anything, that ->bind_param method is superfluous. Just take that off.
public function getData($table)
{
$dataArray = array();
$t = ($table === 'employers') ? 'employers' : 'members';
$query = "SELECT * FROM $t";
$stmt = $this->link->prepare($query);
if($stmt->execute()) {
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$row = array_map('stripslashes', $row);
$dataArray[] = $row;
}
}
return $dataArray;
}
Sample Usage:
$data = $aministrator_query->getData('members');
$tbody = '';
foreach($data as $row) {
$tbody .= "<tr><td>{$row['user_id']}</td><td>{$row['user_password']}</td><td>{$row['user_first_name']}</td><td>{$row['user_last_name']}</td></tr>";
}
$table = sprintf('<table><thead><tr><th>ID</th><th>Password</th><th>First Name</th><th>Last Name</th></tr></thead><tbody>%s</tbody></table>', $tbody);
echo $table;
I am migrating from mysql to mysqli, and I am having trouble returning more than one row from the database in a query.
$db = new mysqli($hostname, $sql_us, $sql_us_pwd, $sql_db); // This is already connected
function db_query($db, $query, $type = 'object') {
global $db;
$result = $db->query($query);
if ($type == 'assoc') {
while($row = $result->fetch_assoc()) {
return $row;
}
} else {
while($row = $result->fetch_object()) {
return $row;
}
}
mysqli_free_result($result);
}
$query = "SELECT * FROM `users`";
$user = db_query($db, $query);
print_r($user); // This is only returning the first row of results
I'm obviously trying to make a function where I can query the database and either return the results in an associative array or as an object. What am I doing wrong?
Use this code:
$rows = array();
if ($type == 'assoc') {
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
} else {
while($row = $result->fetch_object()) {
$rows[] = $row;
}
}
return $rows;
You are using the return inside the while and return terminates the while loop after first iteration that's why you are getting only one row.
You need to store while loop values into array try this
$rows = array();
if ($type == 'assoc') {
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
} else {
while($row = $result->fetch_object()) {
$rows[] = $row;
}
}
return $rows;
When you return in a function it stops executing at that point and goes back to the where it was called from with the value that you are returning.
In your case when you do a return $row, you are getting out of the function as soon as the first row is read.
Fix is:
$result = array();
if ($type == 'assoc') {
while($row = $result->fetch_assoc()) {
$result[] = $row;
}
} else {
while($row = $result->fetch_object()) {
$result[] = $row;
}
}
return $row;
You are only returning the first row. You have to return an array.
$arr = array();
if ($type == 'assoc') {
while($row = $result->fetch_assoc()) {
$arr[] = $row;
}
}
else {
while($row = $result->fetch_object()) {
$arr[] = $row;
}
}
return $arr;
Help me please! How to transfer data from table to smarty?
Function:
public function getBanLog() {
global $mysqli;
$result = $query = $mysqli->query("SELECT * FROM `bans`") or die($mysqli->error);
$rows = array();
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
$rows[] = $row;
}
}
index.php:
$user = new UserInfo();
$smarty = new Smarty();
$smarty->assign("userInfo", $user);
$smarty->assign('ban', $user->getBanLog());
$smarty->display('template/ban.tpl');
ban.tpl:
{foreach from=$ban item=row}
<td>{$row.id}</td>
<td>{$row.banned}</td>
<td>{$row.admin}</td>
<td>{$row.reason}</td>
{/foreach}
Your getBanLog() function returns nothing, need to add a return statement. Also $result = $query = $mysqli->.. is not correct.
Try this
public function getBanLog() {
global $mysqli;
$result = $mysqli->query("SELECT * FROM `bans`") or die($mysqli->error);
$rows = array();
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
$rows[] = $row;
}
return $rows;
}