Pass values from array to a function - php

I have the following code which gets all news:
private function get_news()
{
$news = array();
$query = $this->database->query("SELECT * FROM `news` ORDER BY `news_id` DESC");
while($row = mysql_fetch_array($query))
{
$news[] = $row;
}
return $news;
}
In the same class I have a bbedit() function. I want to get the value of $news[int]['news_content'] and pass it to that function bbedit().

Use $this to call a function within class:
private function bbedit(){
$news = $this->get_news(); // news will have all your array
foreach($news as $key => $val){
// do something with $val['news_content'];
}
}
or
while($row = mysql_fetch_array($query)){
$news[] = $this->bbedit($row['news_content']);
}

Related

fetch_assoc() returning only first row [duplicate]

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;

Recursive Function not working In codeIgniter

I am trying to get all categories with related parent ID with a recursive function.
If i print that array its showing me all data but if i want to return this is not working. I am sure i am doing some mistake.
My code for recursive function is:
public function get_child($id,$level=0){
//$level=0;
$this->db->select('*');
$this->db->from('whole_category');
$this->db->where('parent_id',$id);
$this->db->order_by("id", "ASC");
$query = $this->db->get();
if ($query->num_rows() > 0) {
$res= $query->result();
echo $current_node_id=$res[0]->id;
$level++;
$this->get_child($current_node_id,$level);
$cat["level".$level][] =$res;
return $cat;
}else{
return $cat;
}
}
Calling it like:
public function getcategories(){
echo "<pre>";
$a=$this->get_child(1);
var_dump($a);
}
I had created a Recursive function for a Multi level Marketing Project
Please try it.
public function getSubMembers($memberID, $tableName = 'member_master') {
$data = arra[enter image description here][1]y();
$strQuery = "select MEMBER_ID,LOGIN_NAME,FIRSTNAME,LASTNAME,SPONSOR,PARENT_ID,PAYMENT_STATUS from member_master where SPONSOR='" . $memberID . "' order by POSITION ";
$result = mysqli_query($this->conn, $strQuery);
if (mysqli_field_count($this->conn)) {
while ($row = mysqli_fetch_assoc($result)) {
$data[$row['LOGIN_NAME']] = $row;
foreach ($data as $values) {
$data[$values['LOGIN_NAME']]['SUB'] = $this->getSubMembers($values['LOGIN_NAME']);
}
}
}
return $data;
}

php class return array

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.

PHP + Smarty + MySQL

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;
}

return values from class php oop

the code is as follow:
Class userinfo {
function fetchdatabyemail($email) {
$result=mysql_query(" SELECT * FROM users WHERE email='$email'");
while($row = mysql_fetch_array($result)) {
$name = $row['name'];
$num = $row['num'];
$city = $row['city'];
}
$numrows= mysql_num_rows($result);
}
}
now to get the info I do this :
$info = new userinfo();
$info->fetchdatabyemail('email#email.com');
echo $info->city;
and it doesnt return the info. I think Im doing something wrong any ideas please
do it
public $numrows;
public function fetchDataByEmail($email) {
$result=mysql_query(" SELECT * FROM users WHERE email='$email'");
while($row = mysql_fetch_assoc($result)) {
$fetch[] = $row;
}
$this->numrows = mysql_num_rows($result);
return $fetch;
}
then
$info = new userinfo();
$detail = $info->fetchDataByEmail('email#email.com');
print_r($detail); // return all result array
$info->numrows; // will return number of rows.
Your variable working locally. You need to assign it in class level.
Your code should be:
Class userinfo {
public $name,$city,$num,$numrows;
function fetchdatabyemail($email) {
$result=mysql_query(" SELECT * FROM users WHERE email='$email'");
while($row = mysql_fetch_array($result)) {
$this->name = $row['name'];
$this->num = $row['num'];
$this->city = $row['city'];
}
$this->numrows= mysql_num_rows($result);
}
Then get to the info using this:
$info = new userinfo();
$info->fetchdatabyemail('email#email.com');
echo $info->city;
}
You should have a private variable and getter/setter for it (this is the proper way, see code below). You could also declare $city as a public variable and access directly to it from the class' instance.
class userinfo
{
private $city = '';
public function getCity()
{
return $this->city;
}
public function fetchDataByEmail($email)
{
// Your code here
$this->city = $row['city'];
}
}
$info = new userinfo();
$info->fetchDataByEmail('someone#example.com');
echo 'City: '.$this->getCity();
I think your problem is the scope/visbility of your variables think you need to declare them outside of the scope of the function:
http://www.php.net/manual/en/language.oop5.visibility.php
class userinfo {
public $name;
public $num;
public $city;
public $numrows;
function fetchdatabyemail($email) {
$result=mysql_query(" SELECT * FROM users WHERE email='$email'");
while($row = mysql_fetch_array($result)) {
this->$name = $row['name'];
this->$num = $row['num'];
this->$city = $row['city'];
}
this->$numrows= mysql_num_rows($result);
}
}
You need to first declare the class variables.
class Userinfo {
$city;
// then declare the function
}
The way you were doing it, the scope of $city was only within the function, not stored as a field
while loop in each iteration is updating info.
so, u can echo in the while like
function fetchdatabyemail($email) {
$result=mysql_query(" SELECT * FROM users WHERE email='$email'");
while($row = mysql_fetch_array($result)) {
echo $row['city'];
}
or can store values in an array which is globally declared in the class and than echo the array.
in your code you have $city declared with local function scope which is not accessible from class $info->city.

Categories