how to show all data from joomla table? - php

recently i learned how to get data from database by this method
public static function getdb($params)
{
// Get a database object
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('*');
$query->from('#__categories');
// sets up a database query for later execution
$db->setQuery($query);
// fetch result as an object list
$result = $db->loadObjectList();
foreach ( $result as $row ) {
echo "$row->extension .<br>";
}
}
by this line
echo "$row->extension .<br>";
we get single row value. how to we get all row value of #__categories? by any short code.

The foreach loop should give you all the rows for your query. Try making a few changes like so:
helper.php
public static function getdb($params) {
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('*');
$query->from('#__categories');
$db->setQuery($query);
$result = $db->loadObjectList();
return $result;
}
default.php
$result = modHelloWorldHelper::getdb($params);
foreach ( $result as $row ) {
echo $row->extension . "<br>";
}

You can use another foreach inside
foreach ( $result as $row ) { // it is like foreach($objects as $object)
foreach ($row as $r) { // it is like foreach($object as $values)
echo "$r .<br>";
}
}
But you should print the code in the view not in the model, controller, etc.

Related

Iterate array in Object from Class using fetch(PDO::FETCH_ASSOC)

I've a class with viewData() method that pull the data from the DB table.
I want to return the data result array in Class and iterate the array in Object
I'm able to make it work with fetchAll() but couldn't figure it out how to return the result with fetch() using while loop.
<?php
class CrudClass{
private $db;
function __construct($DB_con){
$this->db = $DB_con;
}
/* DATA VIEW METHOD */
public function viewData(){
$sql = "SELECT * FROM tbl_users";
$stmt = $this->db->prepare($sql);
$stmt->execute();
while($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
return $row; // it doesn't work
}
// below code is working
/*if($stmt->rowCount()>0){
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
}*/
}
}
// instantiate an Object
$obj = new CrudClass($DB_con);
$rows = $obj->viewData();
foreach($rows as $row) {
echo $row['first_name']. " ". $row['last_name'] ."<br>";
}
?>
The reason I want to do that way, because I don't want to pull the data at one go with fetchAll. Instead want to loop through each row at a time. Any help will be appreciated.
You should return array.
$result = []; // initiate the array
while($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
return $result[] = $row; // put each row in the result array
}
return $result; // return the result array
Now the whole method will look something like below
/* DATA VIEW METHOD */
public function viewData() {
$sql = "SELECT * FROM tbl_users";
$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = []; // initiate the array
while($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
return $result[] = $row; // put each row in the result array
}
return $result; // return the result array
}
This way you are assured that even if there is no result set, only array will get returned.
If above doesn't work. Try following two solutions.
1.Test explicitly for false.
while(($row = $stmt->fetch(PDO::FETCH_ASSOC) !== false) {
return $result[] = $row; // put each row in the result array
}
2.Use foreach
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
return $result[] = $row; // put each row in the result array
}
It is possible to return something you can use in a foreach without having to preload all the results (i.e. using PDOStatement::fetchAll()) and without returning the PDOStatement itself -- if that's what you are trying to do.
Because PDOStatement implements Traversable you you can construct an IteratorIterator from the PDOStatement and return that.
class CrudClass
{
public function viewData()
{
$sql = "SELECT * FROM tbl_users";
$stmt = $this->db->prepare($sql);
$stmt->execute();
return new \IteratorIterator($stmt);
}
}
// instantiate an Object
$obj = new CrudClass($DB_con);
$rows = $obj->viewData();
foreach($rows as $row) {
echo $row['first_name']. " ". $row['last_name'] ."<br>";
}
Note that if you were try and foreach over $rows more than once, it will error because because the results of a PDOStatement cannot be rewound.

In Joomla how do I iterate over a database object

Sorry. I am very new to Joomla.
After I load data from the database like this:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('user_id')));
$query->from($db->quoteName('#__user_profiles'));
$db->setQuery($query);
$results = $db->loadObjectList();
How to I show the results?
Try
foreach ($results as $result) {
echo $result->user_id.'<br />';
}

Defining and calling custom function

I have a block of code that works perfect:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select(array($db->quoteName('date')));
$query->from($db->quoteName('#__webfoot_minutes_and_agendas'));
$query->order('date DESC');
$db->setQuery($query);
$results = $db->loadObjectList();
Until I try to assign it to a function:
function call_db() {
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select(array($db->quoteName('date')));
$query->from($db->quoteName('#__webfoot_minutes_and_agendas'));
$query->order('date DESC');
$db->setQuery($query);
$results = $db->loadObjectList();
return $results;
}
It breaks when I try to call the function, I get an error for $results I get, "Invalid argument supplied for foreach()...:
call_db();
foreach ($results as $result) {
$dateArr = explode('-', $result->date);
if (!in_array($dateArr[0], $already_echoed)) {
echo '<li>' . $dateArr[0] . '</li>';
$count++;
}
$already_echoed[] = $dateArr[0];
}
Anyone have any suggestions on how I can straighten out this syntax?
You have to assign result of your function to variable.
$results = call_db();
Though it is awful design:
foreach (call_db() as $result) { ... }
You haven't assigned return value of call_db() to anything. You have to assign it first to $results
$results = call_db();
And, after that it is better if you check that the $results is an array. See this.

joomla 2.5 module: how to foreach loop put in tmpl/default.php

in joomla module to get data from database we use the code
public static function getdb($params)
{
// Get a database object
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('*');
$query->from('#__categories');
// sets up a database query for later execution
$db->setQuery($query);
// fetch result as an object list
$result = $db->loadObjectList();
foreach ( $result as $row ) {
echo "$row->extension .<br>";
}
}
my question is how to use this foreach loop in tmpl/default.php ? and then wat will be my helper.php code?
foreach ( $result as $row ) {
echo "$row->extension .<br>";
}
if i use this foreach loop into default.php then it will better for me. pls someone help
helper.php
public static function getdb($params) {
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('*');
$query->from('#__categories');
$db->setQuery($query);
$result = $db->loadObjectList();
return $result;
}
default.php:
//call the function from the helper.php
$result = modHelloWorldHelper::getdb($params);
//display the results
foreach ( $result as $row ) {
echo $row->extension . "<br>";
}

PHP: letting your own function work with a while loop

$qVraagGroepenOp = "SELECT * FROM $tabele WHERE $where";
$rVraagGroepenOp = mysql_query ( $qVraagGroepenOp );
$aVraagGroepenOp = mysql_fetch_assoc ( $rVraagGroepenOp )
and I converted that to a function
vraagOp("testtable","testtable_ID = $id");
function vraagOp($table,$where)
{
$qVraagOp = "SELECT * FROM $table WHERE $where";
$rVraagOp = mysql_query( $qVraagOp );
$aVraagOp = mysql_fetch_assoc( $rVraagOp );
return $aVraagOp;
}
only the problem is when i need more then one row i need to use a while loop
$qVraagGroepenOp = "SELECT * FROM testtable where testtype = test";
$rVraagGroepenOp = mysql_query ( $qVraagGroepenOp );
while ( $aVraagGroepenOp = mysql_fetch_assoc ( $rVraagGroepenOp ) )
{
echo "testing <br>";
}
It wont work anymore is there a trick to make my function work with this while loop?
This won't work but I want to reach to something like it
while (vraagOp("testtable","testtype = test"))
{
echo "testing <br>";
}
Is this possible?
This could be done with static variables in the function scope.
function vraagOp($table,$where)
{
static $rVraagOp;
if(!$rVraagOp){
$qVraagOp = "SELECT * FROM $table WHERE $where";
$rVraagOp = mysql_query( $qVraagOp );
}
return mysql_fetch_assoc( $rVraagOp );
}
That should do what you're after.
This function returns an array of rows - it's a generic pattern yu can use almost anywhere you get multiple rows from a query.
function vraagOp($table,$where)
{
$sql= "SELECT * FROM $table WHERE $where";
$query= mysql_query($sql);
if ($query != false)
{
$result = array();
while ( $row = mysql_fetch_assoc($query) )
$result[] = $row;
return $result;
}
return $false;
}
//usage
$rows = vraagOp($table,$where);
if ($rows)
{
foreach ($rows as $row)
use($row);
}
This function will 'cache' the mysql result resource from each unique $table/$where combination, and fetch the next result from it on each subsequent call. It will return an associative array for each row, or false when there are no rows left.
function vraagOp($table, $where)
{
// Holds our mysql resources in a map of "{$table}_{$where}" => resource
static $results = array();
$key = $table . '_' . $where;
if (!isset($results[$key]))
{
// first call of this particular table/where
$results[$key] = mysql_query("SELECT * FROM $table WHERE $where");
}
$row = mysql_fetch_assoc($results[$key]);
if ($row === false)
// remove this key so a subsequent call will start over with a new query
unset($results[$key]);
return $row;
}
// Usage
while ($row = vraagOp("table1", "where field > 7")) {
print_r($row);
}
This
while (vraagOp("testtable","testtype = test"))
{
echo "testing <br>";
}
will work if you change VraagOp() to return false when no matching record was found.
You would have to move the mysql_query() part out of VraagOp(), and just leave the mysql_fetch_assoc part in.
However, I can't really see what benefit there would be? You would just be building a (unnecessary) wrapper around mysql_fetch_assoc(), wouldn't you?
You'll need to turn vraagOp() into an iterator and then use foreach() in order to make this work.
Your example won’t work because the condition is executed on every iteration. That means vraagOp("testtable","testtype = test") would be called with each iteration until it returns a falsely value. mysql_fetch_assoc does that but your function doesn’t.
How can we call function inside while loop example is below :
$sql_gpfsF="SELECT * FROM emp_salary";
$result_gpfsF=mysql_query($sql_gpfsF);
while($row_gpfsF=mysql_fetch_assoc($result_gpfsF))
{
call_function();
}
function call_function()
{
echo " Function Called </ br>";
}

Categories