how make loop work out of function in php code? - php

<?php function getnews()
{
global $db;
$news=$db->query("select * from news order by news_id desc");
$row=$news->fetch_object();
return $row;
}?>
`
foreach (getnews() as $result)
{
echo $result->news_title . "<br>";
}
?>
but foreach not work out of function
any help

Your getnews() function only ever returns a single row from the database, even though your query will fetch them all.... perhaps consider a loop in the getnews() function that returns each one in turn, maybe using a generator so that you can use them in a foreach loop
function getnews() {
global $db;
$news=$db->query("select * from news order by news_id desc");
while ($row=$news->fetch_object()) {
yield $row;
}
}
foreach (getnews() as $result) {
echo $result->news_title . "<br>";
}
Though using a generator does require PHP >= 5.5
If you're using an earlier version of PHP, then build an array in getnews() and return that, but it isn't as efficient:
function getnews() {
global $db;
$news=$db->query("select * from news order by news_id desc");
$items = array();
while ($row=$news->fetch_object()) {
$items[] = $row;
}
return $items;
}
foreach (getnews() as $result) {
echo $result->news_title . "<br>";
}

Related

php: variable scope within a class

I am getting started with classes and have a variable scope question. I am defining a variable $query in one function and need to use it in a second function. However, the second function is not seeing it.
I guess I could pass $query to outside the class and then pass it along ($instance->QueryExecute($query);). But that seems messy, there is no need for $query to exist outside the class.
What is the correct way of solving this?
Thank you,
Louis.
<?php
class MyProduct {
public function QueryBuild() {
$query = "SELECT * FROM my_product";
}
public function QueryExecute() {
$result = mysql_query($query);
while ($record = mysql_fetch_assoc($result)) {
foreach ($record AS $key => $value) {
$this->product[$record["pro_id"]][$key] = $value;
}
}
}
}
?>
There are two options to solve your problem and the first is (in my opinion) better than the other:
Option 1: Return value
Just tell your build method to return the value and then use it on your other method:
<?php
class MyProduct {
public function QueryBuild() {
$query = "SELECT * FROM my_product";
return $query;
}
public function QueryExecute() {
$result = mysql_query($this->QueryBuild());
while ($record = mysql_fetch_assoc($result)) {
foreach ($record AS $key => $value) {
$this->product[$record["pro_id"]][$key] = $value;
}
}
}
}
Option 2: Object field
You define a field in your class that holds the query. This, however, means that the method QueryBuild() always has to be called before you can call QueryExecute(), which is not particularly reasonable.
<?php
class MyProduct {
private $query;
public function QueryBuild() {
$this->query = "SELECT * FROM my_product";
}
public function QueryExecute() {
$result = mysql_query($this->query);
while ($record = mysql_fetch_assoc($result)) {
foreach ($record AS $key => $value) {
$this->product[$record["pro_id"]][$key] = $value;
}
}
}
}
Some things to note:
Don't use mysql_* functions. They are deprecated and have been replaced with MySQLi and PDO.
Take a look at coding conventions. Method names should start with a small letter, which makes the code easier to read for everybody used to these standards.
You define a property in the class, that said I would like to add that mysql_* functions are deprecated.
<?php
class MyProduct {
private $query;
public function QueryBuild() {
$this->query= "SELECT * FROM my_product";
}
public function QueryExecute() {
$result = mysql_query($this->query);
while ($record = mysql_fetch_assoc($result)) {
foreach ($record AS $key => $value) {
$this->product[$record["pro_id"]][$key] = $value;
}
}
}
}
?>

Passing mysql result $row to another method in a class

I Have a Main class Employee which fetches Employees Details,Passed Inputs it fetches mysql results and RETURNS into a associate array into $row.
public function Result(){
$this->IsEmptyCheck();
$this->ConnectDb();
$this->QueryDb();
$this->RowCount();
$this->IfEmployeeFound();
}
public function IfEmployeeFound(){
if ($this->row_cnt > 0)
{
while ($row = $this->result->fetch_assoc()){
return($row);
}
}else{echo "No Results" ;}
}
public function CustomhtmlTabledisplay($row){
foreach ( $row as $key => $value ) {
echo .....
echo "<td>".$value['employee_name']."</td>\n";
echo "<td>".$value['age']."</td>\n";
echo "<td>".$value['familydetails']."</td>\n";
echo .....
}
}
I am running the below php call calling the employee class and executing above functions in it like this.
$check = new Employee($employeeid);
$check->Result()->CustomhtmlTabledisplay();
$check->CloseDb();
How can i achieve it ?
I would like to fetch the data by passing the mysql returned rows array from
IfEmployeeFound() into CustomhtmlTabledisplay();
I would like to display employee details by executing this type of query
$check->Result()->CustomhtmlTabledisplay();
(If I understood). For doing next - by executing this type of query:
$check->Result()->CustomhtmlTabledisplay();
You need return $this in end of every method for chaining methods. And store need data in property-fields of your Main Class.
EDIT
If you want use your class like this
$check->CustomhtmlTabledisplay(($check->Result());
change class methods to:
public function Result(){
$this->IsEmptyCheck();
$this->ConnectDb();
$this->QueryDb();
$this->RowCount();
return $this->IfEmployeeFound();
}
public function IfEmployeeFound(){
$out = array();
if ($this->row_cnt > 0){
while ($row = $this->result->fetch_assoc())
$out[] = $row;
}
return empty($out)? null: $out;
}
public function CustomhtmlTabledisplay($rows){
if($rows){
foreach ( $rows as $row) {
echo .....
echo "<td>".$row['employee_name']."</td>\n";
echo "<td>".$row['age']."</td>\n";
echo "<td>".$row['familydetails']."</td>\n";
echo .....
}
}
}
You can use
require_once (employee.php); //employee is the file where you have the methods
And instance the class employee

Assigning SQL Statement to Class Variable

I stated to build up my Database Class.
Here is a part of my database class.
public function query($sql)
{
return $this->getPdo()->query($sql);
}
My Class is working but i want to improve it.
This is external part of class:
$db = new Database();
$q = $db->query('SELECT * FROM table');
while($r = $q->fetch(PDO::FETCH_ASSOC)){
$results[] = $r;
}
echo "<pre>";
print_r($results);
echo "</pre>";
I want to get while part inside database class like
public function query($sql)
{
return $this->getPdo()->query($sql);
}
public function getAll() {
while($r = $this->query($sql)->fetch(PDO::FETCH_ASSOC)){
$results[] = $r;
}
return $results;
}
But i know this part is wrong : $this->query($sql)->fetch(PDO::FETCH_ASSOC); How can i fix it ? I have to declare a class varible like $sql, and i have to assign sql statement to $sql varible.
But i couldn't. How can i do that ?
$q = $db->query('SELECT * FROM table');
$results = $q->fetchAll();
echo "<pre>";
print_r($results);
echo "</pre>";
One of your biggest problems is that when you write
public function getAll() {
while($r = $this->query($sql)->fetch(PDO::FETCH_ASSOC)){
$results[] = $r;
}
return $results;
}
you are causing the database to run the query with each iteration of the loop.
To correct the code as it is defined simply run the query outside of the loop then use fetch as the loop condition:
public function getAll() {
$stmt = $this->query($sql);
while($r = $stmt->fetch(PDO::FETCH_ASSOC)){
$results[] = $r;
}
return $results;
}
Another problem that is probably probably causing you grief is that the $sql value appears to be coming from out of thin air. You should pass it into your getAll function to have access to it.
To avoid all this noise you might want to just follow #YourCommonSense's suggestion and use the available PDO getAll method.
public function getAll($sql){
return $this->query($sql)->fetchAll(PDO::FETCH_ASSOC);
}
You need to pass the $sql parameter to your getAll() method, and then use return to get the result back out. So this method becomes:
public function getAll($sql) {
while($r = $this->query($sql)->fetch(PDO::FETCH_ASSOC)){
$results[] = $r;
}
return $results;
}
Then you use it externally like:
$db = new Database();
$results = $db->getAll('SELECT * FROM table');
echo "<pre>";
print_r($results);
echo "</pre>";

Codeigniter, How to store value from query inside foreach

I have a code like this
$this->load->model("m_crud");
$test= $this->m_crud->get_querry; //this model already have query and result() to return
foreach($test as $retest)
{
echo $retest->primary_id;
$test2=$this->db->query("select * from table2 where id='$retest");
foreach($test2 as $retest2)
{
echo $retest2->name;
}
}
Its easy to just put all this code to "views" but I want to use MCV model.
I tried to store the result using array like this:
$data['test']=$test
foreach($test as $retest)
{
echo $retest->primary_id;
$test2=$this->db->query("select * from table2 where id='$retest");
$data['test2']=$test2
foreach($test2 as $retest2)
{
echo $retest2->name;
}
}
$this->load->view("test_view",$data);
What I got in the view is I have the same value from the echo of $test2, which should be differently by each of $test
thank you, sorry for my bad english
You can use in view page
foreach($test2 as $newarray)
{
foreach($newarray->result() as $row)
{
echo $row->columnnames;//
}
}
It is easy here is an example
Controller Method
function getResult()
{
$this->load->model('mymodel');
$results = $this->mymodel->getRecords();
$data['results'] = $results;
$this->load->view('myview',$data);
}
Model Method
function getRecords()
{
return $this->db->query("select * from table2 where id='$retest")->result_array();
}
And view
foreach($results as $row){
echo $row['id'];
echo '<br>';
echo $row['othercolumn'];
}

PHP Class How to output this method

Hi as I mentioned in last question that I am learning class and method in php so I have another problem to understand how to use this query method to output the result in theme.
I am trying with WordPress at the moment so please consider it. However it is not too generic with WordPress rather the logic.
<?php
class get_user_widget
{
// other mentods are here which is not related to below method
public static function get_users() {
global $wpdb;
$query = "SELECT id, user_login FROM $wpdb->users ORDER BY user_registered DESC";
$users = $wpdb->get_results($query);
// here I am using foreach so is it okay or while loop is right to use?
foreach ($users as $users)
$rs[] = $users;
return count($rs) ? $rs : array();
}
}
?>
So how can I use this in theme to render the output list of user by registered date? I have checked with print_r() and connection and everything is fine and getting output in array but need to use html.
Thanks a lot..
The class can be used like this:
$array = get_user_widget::get_users();
echo "<ul>";
foreach($array as $user) {
echo "<li>".$user->user_login."</li>";
}
echo "</ul>";
EDIT:
class get_user_widget
{
public static function get_users() {
global $wpdb;
$query = "SELECT id, user_login FROM $wpdb->users ORDER BY user_registered DESC";
$users = $wpdb->get_results($query);
if(!empty($users)) {
return $users;
}
else {
$fakeuser = new stdClass();
$fakeuser->user_login = "No users in database";
return array($fakeuser);
}
}
}

Categories