I got below class to fetch records in database, how can use foreach to loop all data in page?
class User{
public function get_user_listing($user_id, $mysqli){
$sql = $mysqli->query("SELECT * FROM `listing` WHERE user_id='".$user_id."'");
if($sql->num_rows > 0){
return $query->result();
}else{
return false;
}
}
}
in my page, if I call:
$user = new User;
$listing = $user->get_user_listing($user_id, $mysqli);
foreach(listing as $value){
echo $value->table_field;
}
But I think that is not a correct way.
You need to return the actual result $sql:
if($sql->num_rows > 0){
return $sql;
} else {
return false;
}
Since you are returning a result set you need to fetch rows:
$user = new User;
$listing = $user->get_user_listing($user_id, $mysqli);
while($row = $listing->fetch_object()){
echo $row->table_field;
}
Or you could add the fetch loop to the class function and return an array of $row[] objects.
Also, I would make some changes here:
private $mysqli;
public function __construct($mysqli) {
$this->mysqli = $mysqli;
}
public function get_user_listing($user_id) {
$mysqli = $this->mysqli;
//or just use $sql = $this->mysqli->query("SELECT * FROM `listing` WHERE `user_id` = '$user_id'");
//etc...
}
Then:
$user = new User($mysqli);
$listing = $user->get_user_listing($user_id);
Better use a prepared statement to protect from SQL injection. And check the returned value from get_user_listing for false or undef.
public function get_user_listing($user_id, $mysqli){
$sql = "SELECT * FROM `listing` WHERE user_id=?";
if ($stmt = $conn->prepare($sql)) {
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
return $result;
}
}
$user = new User;
$result = $user->get_user_listing($user_id, $mysqli);
if(isset($result))
{
while ($row = $result->fetch_assoc()) {
print $row['table_field'];
}
/* free result set */
$result->free();
}
Related
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;
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 am trying to return my mysqli result and store it in a static variable so that I can pass it on to another function. As you can see below the second function needs to be able to read the result from the first one. The scope problem should have been fixed with returning and storing it then storing my function within a variable inside the second function:
What am I doing wrong? Why is this not working? It works for things like my database connection.
function profile_info() {
$connection = database();
static $result;
$query = "SELECT id, name, first_name, last_name, birthdate, occupation, status
FROM users";
$result = mysqli_query($connection, $query);
return $result;
}
I then store the returned result within my function below `$result = profile_info():
function users_overview () {
$connection = database();
$result = profile_info();
echo "<div id='users_overview'>";
while($row = mysqli_fetch_array($result)) {
if (!empty($row['status']) && $row['status'] == 'Online') {
$status = "<div class='online'></div>";
}
else {
$status = "<div class='offline'></div>";
}
include 'php/core/age_converter.php';
include 'php/includes/profile_information.php';
}
echo "</div>";
}
users_overview();
Seems two time $connection = database(); is being called when you include the call to profile_info(); from users_overview ()
Check now if it works now,
function profile_info() {
$connection = database();
static $result;
$query = "SELECT id, name, first_name, last_name, birthdate, occupation, status
FROM users";
$result = mysqli_query($connection, $query);
return $result;
}
function users_overview () {
$result = profile_info();
echo "<div id='users_overview'>";
while($row = mysqli_fetch_array($result)) {
if (!empty($row['status']) && $row['status'] == 'Online') {
$status = "<div class='online'></div>";
}
else {
$status = "<div class='offline'></div>";
}
include 'php/core/age_converter.php';
include 'php/includes/profile_information.php';
}
echo "</div>";
}
users_overview();
As you don't want to globally define the variable and you can use the OOPs Concept. Data will be wrap in object. I wrote a code for you.
class user{
private $conn;
private $result;
function __construct(){
$conn1 = new mysqli("localhost", "root", "", "siteData");
$this->setConn($conn1);
}
public function profile_info(){
$query = "SELECT * FROM users";
$num = $this->getConn();
$result = $num->query($query);
return $result;
}
function users_overview () {
$result = $this->profile_info();
while($row = mysqli_fetch_array($result)){
//get your result
}
}
function setConn($conn1){
$this->conn = $conn1;
return $this->conn;
}
function getConn(){
return $this->conn;
}
}
$temp = new user();
$temp->users_overview();
I tried to get followers from MySQL usingy this class
class get_followers {
public $followers_arr = array();
public function __construct($user_id) {
$query = "select * from followsystem where following ='$user_id'";
$q = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($q);
if ($count > 0) {
while ($row = mysql_fetch_assoc($q)) {
array_push($this->followers_arr, $row['userid']);
}
}
return $this->followers_arr;
}
}
Then I initialize this class
$fol = new get_followers($userid);
$fol_arr = json_encode($fol);
echo $fol_arr;
Then I get
{"followers_arr":["1234","456"]}
but what i want want just to get this
["1234","456"]
How is that works?
I don't think you understand how constructors work. You can't return a value from a constructor because it's just used to instantiate the object. When you're doing $fol_arr = json_encode($fol); you're actually encoding the entire object, not it's return value.
If you really want to use a class to do this, you should add a method to the class and use that, like this:
class Followers {
public $followers_arr = array();
public $user_id = null;
public function __construct($user_id) {
$this->user_id = $user_id;
}
public function get()
{
$query = "select * from followsystem where following ='{$this->user_id}'";
$q = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($q);
if ($count > 0) {
while ($row = mysql_fetch_assoc($q)) {
array_push($this->followers_arr, $row['userid']);
}
}
return $this->followers_arr;
}
}
And use it like this:
$fol = new Followers($userid);
$fol_arr = json_encode($fol->get());
echo $fol_arr;
The solution to your problem is to do $fol_arr = json_encode($fol->followers_arr);
Nonetheless, making a class in this case is completely obsolete, since you only make it as a wrapper for a single function you want to execute (called get_followers) Instead of making a class, you could simply make the following:
function get_followers($user_id) {
$followers_arr = [];
$query = "select * from followsystem where following ='$user_id'";
$q = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($q);
if ($count > 0) {
while ($row = mysql_fetch_assoc($q)) {
array_push($followers_arr, $row['userid']);
}
}
return $followers_arr;
}
$fol = get_followers($userid);
$fol_arr = json_encode($fol);
echo $fol_arr;
There is no need to put it in a class unless the class serves the purpose of combining a few functions and variables to create a behaviour.
I am trying to return all the productnames from my MySQL table. At the moment this only returns the first name in the column
public function selectAll ()
{
$stmt = Database::get()->query('SELECT * FROM retrofootball_products');
while($row = $stmt->fetch())
{
return $row['productname'];
}
}
How do I get it to loop through and select all the productnames?
One way you could do is just select only the productname column, and then use $stmt->fetchAll(PDO::FETCH_ASSOC).
public function selectAll ()
{
$stmt = Database::get()->query('SELECT `productname` FROM retrofootball_products');
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
do:
public function selectAll () {
$stmt = Database::get()->query('SELECT * FROM retrofootball_products');
$allCols = array();
while($row = $stmt->fetch()) {
$allCols[] = $row['productname'];
}
return $allCols;
}
You are directly returning first value that was causing the problem.
Store each record in array and return that array.
public function selectAll ()
{
$stmt = Database::get()->query('SELECT * FROM retrofootball_products');
while($row = $stmt->fetch())
{
$arr[] = $row['productname'];
}
return $arr;
}
You can just avoid looping through as you're using PDO and use fetchAll.
public function selectAll ()
{
$stmt = Database::get()->query('SELECT * FROM retrofootball_products');
return $stmt->fetchAll();
}
http://php.net/manual/en/pdostatement.fetchall.php
While I'm new to stmp too, I imagine this might work
$result = $stmt->get_result();
while ($row = $result->fetch_assoc())
{
// do something with $row
}