PHP Class How to output this method - php

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

Related

PHP method can't return two dimensional array?

Hello I stuck on really strange thing.
I'm writing simple PHP MVC WebApp for school project and I can't return two dimensional array.
I solve this problem this way:
class Post{
public $author;
public $cat;
public $table;
function getPosts($cat = ""){
dbstart();
global $dbconn;
empty($cat) ? $query = mysqli_query($dbconn, "SELECT * FROM pytania") : $query = mysqli_query($dbconn, "SELECT * FROM pytania WHERE cat = $cat");
while($row = mysqli_fetch_assoc($query)){
$output[] = $row;
$this -> table = $output;
dbstop();
}
}
}
It works perfectly when I'm calling property in controller
"poststable" => $post -> table
Gives me all four posts (two dimensional array with 4 rows) but I want to remove public $table property so I can directly call method like this way:
"poststable" => $post -> getPosts($cat)
Unfortunately, when I change my method code with this:
return $output;
$data "poststable" Gives me only first post (array stores only one post)
Anyone has idea what I'm doing wrong? Thanks in advance for help!
You need to build up the entire output in the while loop, after which you can return it. In addition, you should do your DB clean up outside the loop.
<?php
class Post{
public $author;
public $cat;
function getPosts($cat = ""){
dbstart();
global $dbconn;
empty($cat)
? $query = mysqli_query($dbconn, "SELECT * FROM pytania")
: $query = mysqli_query($dbconn, "SELECT * FROM pytania WHERE cat = $cat");
// Use an array as your return value
$output = [];
while($row = mysqli_fetch_assoc($query)){
// Build up the array
$output[] = $row;
}
// Do your clean up out here
dbstop();
// Now return the result
return $output;
}
}

How to access the fetched object property that is encapsulated within the SQL function count()?

I have the following function:
public function count () {
global $db;
$query = "SELECT COUNT(post_id) FROM posts";
$result = $db->select($query);
return $result;
}
This then links to another function:
public function select($query) {
$results = $this->connection->query($query);
while ($obj = $results->fetch_object()) {
$r[] = $obj;
}
if (!empty($r)) {
return $r;
} else {
return false;
}
}
The output is in a form of an array of objects.
Normally I could access the property of that object to get the result.
$result[0]->property
But in this case, the property is encapsulated in the function count(). How can I access that property?
I have utilized a workaround by simply selecting the number of rows from the query. But I still want to know how can I access that property via COUNT().
public function count () {
global $db;
$query = "SELECT * FROM posts";
$result = $db->initiate_query($query)->num_rows;
return $result;
}
public function initiate_query($query) {
$result = $this->connection->query($query);
return $result;
}
Thank you in advance,
Robert
First of all try to use var_dump() on fetched object. That should give you suggestions. I do believe that it is something like $object->count by default in most DBMS engines.
Second option (that I do really prefer in my code) is to use alias on COUNT()ed field:
SELECT COUNT(post_id) as tmp_value FROM posts
Then you should access it as predefined alias states: $object->tmp_value.
In the end you should get something like this:
public function count(){
global $db;
$query = "SELECT COUNT(post_id) as tmp FROM posts";
$result = $db->select($query);
return $result[0]->tmp;
}

PHP OOP query is not executing

I am using PHP with OOP to select rows from the database (MySQL).
When I execute the query, it returns an empty row.
Here is the classe I am using:
<?php
class EmploiManager
{
private $_db;
public function __construct($db)
{
$this->setDb($db);
}
public function category($category)
{
$q = $this->_db->prepare('SELECT * FROM DemandeEmploi WHERE category = :category');
$q->execute(array('category' =>$category));
$donnees = $q->fetch(PDO::FETCH_ASSOC);
return new Emploi($donnees);
}
public function setDb(PDO $db)
{
$this->_db = $db;
}
}
$type = $_GET['category'];
$manager = new EmploiManager($db);
$row = $manager->category($type);
foreach ($row as $demandeE)
{
?>
<div class="list"><h4><? echo $demandeE->title();?></h4> </div>
<?php
}
?>
Can any one tell me what's wrong with that code?
Thanks!
It's my bad, I didn't use a loop to select all the rows.
I corrected the code and it works fine now, here is what it looks like:
public function category($category)
{
$datas = array();
$q = $this->_db->prepare('SELECT * FROM DemandeEmploi WHERE category = :category');
$q->execute(array('category' =>$category));
while ($donnees = $q->fetch(PDO::FETCH_ASSOC))
{
$datas[] = new Emploi($donnees);
}
return $datas;
}
$q->fetch() just returns one row of the results. If you want all the results, you must use $q->fetchAll().
Since you specified PDO::FETCH_ASSOC, the elements of $row will be associative arrays, not objects; aren't you getting errors saying that you're trying to call a method on a non-object? So $demandeE->id() should be $demandeE['id'], and $demandeE->title() should be $demandeE['title'].
Alternatively, you could specify PDO::FETCH_OBJ. Then, the values will be properties, not methods, so it should be $demandeE->id and $demandeE->title (no parentheses).

Multiple Query in one model in joomla 2.5

Can I do 2 separate queries in a model in joomla 2.5 ?
If it is possible, how do you do this?
This is my model:
<?php
defined('_JEXEC') or die();
jimport( 'joomla.application.component.modellist' );
class AnagraficheModelServiziassociatiaggiuntivi extends JModelList
{
public function __construct($config = array())
{
if (empty($config['filter_fields']))
{
$config['filter_fields'] = array('id_servizi_aggiuntivi', 'id_persona', 'id_servizio', 'nome_servizio', 'cod_servizio', 'id_tipologia_socio', 'nome_servizio');
}
parent::__construct($config);
}
function getListQuery()
{
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('id_servizi_aggiuntivi, id_persona , id_servizio , nome_servizio');
$query->from('#__servizi_aggiuntivi as serviziaggiuntivi, #__elenco_servizi');
$query->where('cod_servizio=id_servizio');
$result1 = $db->loadObjectList();
//$db->setQuery($query);
$query = $db->getQuery(true);
$query->select('id_tipologia_socio, id_servizio as cod_servizio, nome_servizio');
$query->from('#__associazione_servizi as serviziassociati, #__elenco_servizi');
$query->where('cod_servizio=id_servizio');
$result1 = $db->loadObjectList();
return $query;
}
protected function populateState($ordering = null, $direction = null)
{
// Load the filter state.
$search = $this->getUserStateFromRequest($this->context.'.filter.search', 'filter_search');
$this->setState('filter.search', $search);
// List state information.
parent::populateState($ordering, $direction);
}
}
?>
This doesn't work, but if I delete the second query it works great!
In my opinion, the problem is in the function getListQuery(). In this function I want insert 2 queries not 1 query! Is it possible?
The short answer is no. getListQuery should return a query. You can't get it to return two queries.
Instead, you likely want to override the getItems function to process the items after the first query runs. You can either adjust or add items using something like the following:
public function getItems() {
// load items from the parent getItems function, which will call getListQuery to handle your first query.
//It only adds items if the first query works.
if ($items = parent::getItems()) {
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('id_tipologia_socio, id_servizio as cod_servizio, nome_servizio');
$query->from('#__associazione_servizi as serviziassociati, #__elenco_servizi');
$query->where('cod_servizio=id_servizio');
$result1 = $db->setQuery($query)->loadObjectList();
// this is a simple way to merge the objects. You could do other processing (loops, etc) to meld the information together
$items = (object) array_merge((array) $items, (array) $restult1);
}
return $items;
}

PHP simple function not working

I can't make a simple echo.
I have an admin.class.php
public static function get_quota() {
return self::find_by_sql("SELECT * FROM quota");
}
public static function find_by_sql($sql="") {
global $database;
$result_set = $database->query($sql);
$object_array = array();
while ($row = $database->fetch_array($result_set)) {
$object_array[] = self::instantiate($row);
}
return $object_array;
}
And my echo code in index.php
<?php
$admin = User::find_by_id($_SESSION['user_id']);
$admin_class = new Admin();
$get_quota = Admin::get_quota();
$sql = "SELECT * FROM quota";
$get_quota = Admin::find_by_sql($sql);
?>
.
.
.
<?php echo $get_quota->daily_a; ?>
So my problem is, that the code is not working. I cannot echo my data. Can you help me, please?
You have a couple of problems here:
<?php echo $get_quota->daily_a; ?>
This line references the $get_quota variable and searches for a member field daily_a. Try this:
<?php echo "Quota is:".var_export($get_quota->daily_a,true); ?>
This will show that that is simply an empty variable.
However, also note:
$get_quota = Admin::get_quota();
$sql = "SELECT * FROM quota";
$get_quota = Admin::find_by_sql($sql);
Here you are calling two separate methods from Admin and setting the variable $get_quota to the result. The second overwrites the first. Therefore the get_quota() method doesn't help us here: we need to know what your find_by_sql() method returns.
EDIT (Post new code added to question)
You can implement logging/echoing within the function you've a problem with:
public static function find_by_sql($sql="") {
global $database; //Note this is bad practice (1).
$result_set = $database->query($sql);
echo "Result Set: ".var_export($result_set,true)."\n";//This should return something if you're getting something back from the database. Also, remove this for runtime (obviously).
if (count($result_set) <= 0) { //constraint checking is always good! And cheap!
error_log("An unexpected number of rows (0) was received from the database for query='".$sql."'.");
}
$object_array = array();
while ($row = $database->fetch_array($result_set)) {
$object_array[] = self::instantiate($row); //Ensure that the instantiate function returns something!
}
echo "Object Array: ".var_export($object_array, true)."\n";//double-check your instantiate function is working
return $object_array;
}
Based on this code, your problem is likely with the instantiate function; if it's not returning anything, $object_array is probably empty. (But not null!).
(1) You should avoid grabbing global variables like this. Instead, instantiate a class that holds and manages your database connection. Then make your find_by_sql function non-static and have a member field pointing to your database.

Categories