getting list of users in Drupal 7 using PHP - php

How can I fetch user names from a Drupal 7 database using PHP?
See this:
Is it possible to use the Drupal api to get a list of users?
This is for Drupal 6 and I have tried this but it says
Call to undefined function db_fetch_object()
Here is my code:
$result = db_query("SELECT name AS users_name FROM {users}");
while($row = db_fetch_object($result)) {
print_r($row);
}

Lets give it a try
$query = db_select('users', 'u');
   $query->fields('u', array('name'));
   $result = $query->execute();
   while($record = $result->fetchAssoc()) {
        print_r($record['name']);
   }

In Drupal 7 you can fetch all the users using entity_load,
To get the user names alone use the following,
$users = entity_load('user');
$user_names = array();
foreach ($users as $user_id => $user) {
$user_names[] = $user->name;
}

user_load_multiple
Example from modules\profile\profile.pages.inc :
$users = user_load_multiple($uids);
$content = '';
foreach ($users as $account) {
$profile = _profile_update_user_fields($fields, $account);
$content .= theme('profile_listing', array('account' => $account, 'fields' => $profile));
}
Note that in drupal 7 all things happen via entity. It's not so fast, but flexible...

$query = db_select('users', 'u');
$query
->condition('u.uid', 0, '<>')
->fields('u', array('name'));
$result = $query->execute();
Here's the whole documentation for Drupal 7 Database api

Your code was almost correct if you had changed your while statement to read
while ($result as $row)
db_fetch_object is no longer needed in d7
it would have worked. Although db_select calls specified in this post will work, they require more overhead and should be avoided unless you are trying to generate dynamic queries. Also see: http://drupal.org/node/224333 for info on how the apis have chaned between d6 and d7. A search for db_fetch_object on this page would've given this info.

My example code to get the list of users from drupal site,
$all_users = entity_load('user');
foreach($all_users as $value) {
$user_list = (array)$value;
$users[$user_list['uid']] = $user_list['name'];
}
Now you can get the answer from the array variable $users.
For example if you want to list all the user other than administrator (default user) means use the below example:
$all_users = entity_load('user');
foreach($all_users as $value) {
$user_list = (array)$value;
if($user_list['uid'] > 1) {
$users[$user_list['uid']] = $user_list['name'];
}
}
In the above both example, the id of each user is placed as array index and the name of each usder is saved as array value.

Drupal 7 introduces a new concept of Entity.
User also included in Entity now.
You can use following function entity_load() to get the details of all entities.
To fetch the usernames in array :
$users = entity_load('user');
$usernames = array();
foreach($users as $id => $user){
$usernames[$user->uid] = $user->name;
}
print_r($usernames);
Thanks

A Better way
function GetAllActiveUsers() {
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'user')
->propertyCondition('status', 1);
$results = $query->execute();
$uids = array_keys($results['user']);
return $uids;
}
This will return all active users and use the code in a function to use it as a helper

Try this:
$query = db_select('users', 'u')
->fields('u')
->execute();
while($result = $query->fetchAssoc()) {
print_r($record['name']);
}

You can try this as well,
$query = db_select('users', 'u');
$query->fields('u', array('uid, name'));
$result = $query->execute();
while($record = $result->fetchAssoc()) {
$account = user_load($record['uid']);
if($account->uid){
print $account->name;
}
}

Simplified example with fetchAll():
$users = db_select('users', 'u')
->fields('u', array('uid'))
->execute()
->fetchAll();
foreach ($users as $user) {
$full_user = user_load($user->uid);
//do your stuff here
}

Related

I only want to return users who where isactive = 1

I am still learning php - but I want to modify a working php page and check a MySQL table for isactive then only return users if it is set to 1.
The page originally said:
foreach ($users as $U) {
if (!$U['name'])
list($name) = explode('#', $U['default_email__address']);
else
$name = new UsersName($U['name']);
I tried this, but it isn't working:
foreach ($users as $U) {
if ($U->filter(array('isactive' => 1)));
if (!$U['name'])
list($name) = explode('#', $U['default_email__address']);
else
$name = new UsersName($U['name']);
and the rest of the page works fine. I am not sure if I should add my if statement at the top of the page, before the "foreach" or as part of the "foreach". I am not even positive I have correct way to pull the field value.
$U appears to be an associative array. They aren't objects with methods. If you want to get isactive, just use $U['isactive']
foreach ($users as $U) {
if ($U['isactive') {
if (!$U['name']) {
list($name) = explode('#', $U['default_email__address']);
} else {
$name = new UsersName($U['name']);
}
}
}

Instantiating objects foreach and mysqli results

hopefully this can make sense.
I want to be able to do something like this
<?php
require_once("inc/database_connection.php");
require_once("classes/Users.php");
$users = Users::GetAllUsers($dbConn);
foreach($users as $user) {
echo $user->GetUserName();
}
?>
I see that it is available in code igniter's result() set function - http://www.codeigniter.com/user_guide/database/results.html
but I would really like to add it into my database class.
The GetAllUser method should contain something like:
$res = mysqli_query(...);
$results = array();
while ($row = mysqli_fetch_assoc($res)) {
$results[] = new User($row['userid'], $row['username'], $row['email'], ...);
}
return $results;

get array values with a function in PHP

What is the proper way to create a function to get array values from a query? I am getting "Undefined index: page_title" error.
However I can get the value without function like: echo $row->page_title;
Or echo $query[0]->title;
function get_page($id) {
$db = new DB();
$query = $db->get_rows("SELECT * FROM pages WHERE id = :id ", array('id' => $_GET['id']) );
foreach ($query as $row) {
$page_id = $row->id;
$page_title = $row->title;
}
return $query;
}
$page = get_page(1);
echo $page['page_title'];
here is my database class:
function get_rows($query, $values=array(), $fetchType = FETCH_OBJ)
{
$sth = $this->dbh->prepare($query);
if(is_array($values) && (sizeof($values) > 0))
{
foreach($values as $key=>$val)
{
$key = is_numeric($key) ? ($key + 1) : $key;
$sth->bindValue($key,$val);
}
}
if($sth->execute())
return $sth->fetchAll($fetchType);
}
To make the function reusable, I would rewrite it the following way
function get_page($id, $col) {
$db = new DB();
$query = $db->prepare('SELECT * FROM pages WHERE id = :id');
$query->execute(array(':id' => $id));
$results = $query->fetch(PDO::FETCH_NUM);
return $results[0][$col];
}
$page = get_page(1, 'page_title');
echo $page;
I skipped the foreach as you said that all id's are unique so you should only ever have 1 result
Also it may not be a bad idea to add some error checking to make sure you do get back what you expect from the query and to make sure it is not empty.
Edit: Sorry if the syntax is a little off, dont have anything to test the code against quickly.

foreach loop in Zend Framework 1 wont return multiple results in json output

I have built up a script to first query table 'linkags' in database for id's where 'id' is equal to 'userId' and 'type' is equal to 'type'.
I then use the result to query table 'linktagRevisions' to fetch the latest revision for the returned array of id's pertaining to that user.
I then output the list of 'linktagRevisions' in to a json output.
My issue has been that I have been unable to unserialize 'content'. So in building my array to output in json I have coded:
$data = array('linktag' => unserialize($result[$linkI]['content']));
Which successfully returns an unserialzed result, but it limits to one row even with the foreach loop in place. How can I use the loop to fetch all rows?
Here is my full code:
public function testAction()
{
//Return list of tags for the defined user and make default type 10
$u = 2;
$t = 10;
$resultid = array();
//Connect to database
$db = Zend_Db_Table::getDefaultAdapter();
$select = $db->select()
->from(array('lt' => 'Linktags'),
array('id'))
->where('userId = ?', $u)
->where('type = ?', $t);
$stmt = $select->query();
$resultid = $stmt->fetchAll();
//print_r($resultid);
//Get latest revision from database and loop through $id's
$id = $resultid;
//print_r($id);
//setup array and loop
$result = array();
foreach($id as $lId_all) {
foreach($lId_all as $lId) {
//Connect to database
$db = Zend_Db_Table::getDefaultAdapter();
//Perform Query
$select = $db->select('')
->from(array('lr' => 'LinktagRevisions'),
array('content'))
->where('linktagId = ?', $lId)
->order('updated DESC')
->limit(1);
$stmt = $select->query();
$result[$lId] = $stmt->fetch();
}
}
$linkId = $resultid;
foreach ($linkId as $linkI_all) {
foreach ($linkI_all as $linkI) {
//print_r($linkI);
$data = array('linktag' => unserialize($result[$linkI]['content']));
}
print_r($data);
$this->_helper->json($data, true);
}
}
Try to add link index like this:
$data = array();
foreach ($linkId as $linkI_all) {
foreach ($linkI_all as $linkI) {
$data['linktag'.$linkI] = unserialize($result[$linkI]['content']);
}
}
$this->_helper->json($data, true);

How to through multidimensional array in Codeigniter?

I'm trying to get my head around grabbing all variable I need in Codeigniter and then passing those values to the view.
I understand the concept, but am getting stuck on iterating through an array and adding on another array to each of its keys.
The $data['items'] array contains data passed from a model via the get_all() function. The query is basically "Select * from items".
Each item has multiple features and pictures. In order to get the appropriate values I need the id of an item. I can grab this from the first array ($data['items']) which I can then pass to a model function.
I keep getting various errors when trying to do this via the code below. I've tried defining the features and pictures arrays before the foreach loop - still get errors.
I'm sure my syntax is just wrong. Any help is welcome.
$data['items'] = $this->amazon->get_all();
foreach ($data['items'] as $data )
$id = $data->id;
$data['features'] = $this->amazon->get_features($id);
$data['pictures'] = $this->amazon->get_pictures($id);
}
Edit
Based on feedback I've updated the code to this (lines 24 - 30 of the code):
$items = $this->amazon->get_all();
for($i=0; $i<count($items);$i++) {
$data = $items[$i];
$id = $data->id;
$items[$i]['features'] = $this->amazon->get_features($id);
$items[$i]['pictures'] = $this->amazon->get_pictures($id);
}
PHP is complaining with this:
PHP Fatal error: Cannot use object of type stdClass as array in /var/www/ci/application/controllers/main.php on line 28
Here are the functions from the amazon model:
function get_all()
{
$query = $this->db->get('items');
return $query->result();
}
function get_pictures($id) {
$query = $this->db->query("SELECT link FROM pictures WHERE item_id='$id' AND type IN('thumb_set')");
$style = "border-style:solid; border-width:1px";
$class = "modal-thumb";
$results = '';
foreach ($query->result() as $row) {
$results .= "<li style='$style' class='$class'><img src='$row->link' alt=''/></li>";
}
return $results;
}
function get_features($id) {
$query = $this->db->query("SELECT content FROM features WHERE item_id='$id' ORDER BY feature_num DESC");
$results = '';
foreach ($query->result() as $row) {
$results .= "<li>";
$results .= $row->content;
$results .= "</li>";
}
return $results;
}
I'm thinking i need to use 'results_array()' instead of 'results()'? Are my results returned as an object instead of an array the way things are now?
As you said, you have syntax error in the foreach statement, you are redefining the $data array.
foreach ($data['items'] as $data )
Try this:
$items = $this->amazon->get_all();
for($i=0; $i<count($items);$i++){
$data = $items[$i];
$id = $data->id;
$items[$i]['features'] = $this->amazon->get_features($id);
$items[$i]['pictures'] = $this->amazon->get_pictures($id);
}

Categories