So I am having trouble getting the information I pull from the database order according to the id in my database. I wrote the following function based on a tutorial in a book ('Pro Zend Framework Techniques' published by Apress) and the book is riddled with typos and mistakes so i'm hoping it is something im just overlooking.
public function getRecentArticles ($count = 99, $namespace = 'article')
{
$select = $this->select();
$select->order = 'id DESC';
$select->where('namespace = ?', $namespace);
$select->limit($count);
$results = $this->fetchAll($select);
if ($results->count() > 0) {
$articles = array();
foreach ($results as $result) {
$articles[$result->id] = new Rt_Content_Item_Article($result->id);
}
return $articles;
} else {
return null;
}
}
As you can see, I am trying to arrange the articles in descending order based on the ID field in the database. Any advice would be great.
Thanks.
$select = $this->select ()
->order ('id DESC')
->where ('namespace = ?', $namespace)
->limit ($count);
order is a function, same as where and limit. So your order line should be:
$select->order('id DESC');
Related
I have a problem where some variables are probably (I can't know for sure) not inserted into the final statement. Here is my example:
Works:
public static function findByPageAndFieldContains($recordsPerPage, $page, $field, $searchterm) {
$query = CouchbaseN1qlQuery::fromString('SELECT * FROM `public_portal` WHERE `collection`=$collection AND TOSTRING('.$field.') LIKE "%'.$searchterm.'%" ORDER BY `_id` limit $limit offset $offset');
$query->options['$collection'] = static::COLLECTION_NAME;
//$query->options['$field'] = $field;
$query->options['$limit'] = $recordsPerPage;
$query->options['$offset'] = $recordsPerPage*($page-1);
//$query->options['$searchterm'] = $searchterm;
$result = DB::getDB()->query($query);
var_dump($query);
var_dump($result);
$objects = array();
foreach($result as $row) {
$object = new static($row->{"public_portal"});
$object->setId($row->{"public_portal"}->{"_id"});
$objects[] = $object;
}
//var_dump($objects);
return $objects;
return $result;
}
Debug Output:
debug01
Does not work:
public static function findByPageAndFieldContains($recordsPerPage, $page, $field, $searchterm) {
$query = CouchbaseN1qlQuery::fromString('SELECT * FROM `public_portal` WHERE `collection`=$collection AND TOSTRING($field) LIKE "%$searchterm%" ORDER BY `_id` limit $limit offset $offset');
$query->options['$collection'] = static::COLLECTION_NAME;
$query->options['$field'] = $field;
$query->options['$limit'] = $recordsPerPage;
$query->options['$offset'] = $recordsPerPage*($page-1);
$query->options['$searchterm'] = $searchterm;
$result = DB::getDB()->query($query);
var_dump($query);
var_dump($result);
$objects = array();
foreach($result as $row) {
$object = new static($row->{"public_portal"});
$object->setId($row->{"public_portal"}->{"_id"});
$objects[] = $object;
}
//var_dump($objects);
return $objects;
return $result;
}
Debug output:
debug02
Basically the second example returns no result, while the first one works just fine.
Any idea why?
You are not using N1QL parameters correctly. You must decide if you are evaluating your parameters in PHP or in N1QL.
The field name cannot be a N1QL parameter, so you evaluate it in PHP:
TOSTRING('.$field.') LIKE ...
The search term should be a N1QL parameter, so you add wildcards in PHP and then pass it to N1QL as a parameter:
$searchterm = '%'.$searchterm.'%'
TOSTRING('.$field.') LIKE $searchterm ...
fetchresultsAction
public function fetchresultsAction() {
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
//$form_data = $this->getRequest()->getPost();
//$examcatID = $form_data['examcatID'];
$examID = 'Exam_ID_001';
$Exam_Results = new Admin_Model_Examresults();
$results = $Exam_Results->fetchExamResults($examID);
foreach ($results as $value) {
print_r($value['subjectID']);
echo '<br/>';
}
}
Model > Examresults
public function fetchExamResults($examID) {
$sel = $this->select();
$sel->distinct();
$sel->where('examID=?', $examID);
$result = $this->fetchAll($sel); // fetch the rows to the array called result
return $result;
}
This Code is not work.I need have to get NON-Duplicate values of subjectID from mysql database.How Can I do that.Please help me to solve this problem.
Note : This is Zend 1.12 version
Try using print_r($value->subjectID)
i have a problem with php in arrays.
i have a db table like that , it shows applications to job.
What i want is to order job titles with their files for example
title must be shown :
WEB Tasarım Uzmanı
noktamedya.com/CVs/zsdfsdfsdfsdfsdf.docx
noktamedya.com/CVs/zsdfsdfsdfsdfsdf.docx
İçerik Yöneticisi
noktamedya.com/CVs/abc.docx
noktamedya.com/CVs/abc.docx
i have a class which takes to important record from db
public function getAllRec()
{
$query = "SELECT * FROM applyRecords ";
$resultDb = $this->db->query ($query);
$jobs = array ();
while ( $row = $resultDb->fetchObject () ) {
$job = new Job ();
$job->title = $row->jobTitle;
$job->url = $row->file;
$jobs [] = $job;
}
return $jobs;
}
i have here to file and jobTitle.
in admin inc. i call this function like that
$jobs3 = $jobHome->getAllRec();
and try to order with their jobTitle but have error and dont understand
foreach($jobs3 as $job)
{
$groupJobs = [$job->title][$job->url] = $job;
}
what's wrong here?
I think this is what you are trying to do:
Group job applications by title of job applying to
$groupJobs = array();
foreach($job3 as $job){
if(!isset($groupJobs[$job->title])){
$groupJobs[$job->title] = array();
}
$groupJobs[$job->title][] = $job; // add job to group
}
Instead of ordering in PHP, order in SQL, and then continue.
Instead of
"SELECT * FROM applyRecords "
try
"SELECT * FROM applyRecords ORDER BY jobtitle "
Try something like this:
$groupJobs[$job->title] = array(
$job->url => $job
);
The groupJobs Array Must be defined as Array before foreach.
And remember, $job is an object.
Just sort the records at the time of database fetch
"SELECT * FROM applyRecords ORDER BY jobTitle"
$groupJobs = [$job->title][$job->url] = $job;
This is not valid php syntax. I can't even see what are you trying to do here but I make a wild guess:
$groupJobs[] = array(
"title" => $job->title,
"urls" => array($job->url1, $job->url2)
);
About the ordering: You should add a parameter for this and let sql do to ordering:
public function getAllRec($order)
{
$query = "SELECT * FROM applyRecords ";
if ($order) $query .= " ORDER BY " . $order;
$resultDb = $this->db->query ($query);
...
My final answer is below
$groupJobs = array();
foreach($jobs3 as $job)
{
$groupJobs[$job->title][] = $job;
}
foreach($groupJobs as $key => $value){
$key . "<br />";
foreach($value as $node){
$node->url;
$node->name;
}
}
Thank you all.
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
}
Hey, so thanks to the help earlier, I now have a great function for querying a specific row of data.
class Posts{
public static function singleQuery($table, $value){
return mysql_fetch_object(
mysql_query("select * from $table where id=$value"), __CLASS__);
}
}
$set = Posts::singleQuery('settings', '1');
echo $post->title;
I was hoping to modify this so it queries the following:
SELECT * FROM posts ORDER BY id DESC LIMIT 0, 3"
and then create an 'echo loop' or a foreach type of deal on my view/index page. Something like:
foreach ($a as $b){
echo "yadda"
}
I hope this makes sense..
$result = mysql_query("SELECT * FROM posts ORDER BY id DESC LIMIT 0, 3"), __CLASS__);
while($object = mysql_fetch_object($result)) {
// each round of while has the next line in $object
$return[] = $object;
}
return $return;
...
$array = Posts::multipleQuery(...);
foreach($array AS $row) {
echo $row->title;
}