Drupal - Unable to get result from db_query - php

I have written below code in drupal module.
echo '<pre>';
$data = db_query("SELECT uid, name, status, created, access FROM {users} u WHERE uid <> 0 LIMIT 50 OFFSET 0");
print_r($data);
die;
But it is not giving me users data it is giving me below output:
DatabaseStatementBase Object
(
[dbh] => DatabaseConnection_mysql Object
(
[needsCleanup:protected] =>
[target:protected] => default
[key:protected] => default
[logger:protected] =>
[transactionLayers:protected] => Array
(
)
[driverClasses:protected] => Array
(
[SelectQuery] => SelectQuery
)
[statementClass:protected] => DatabaseStatementBase
[transactionSupport:protected] => 1
[transactionalDDLSupport:protected] =>
[temporaryNameIndex:protected] => 0
[connectionOptions:protected] => Array
(
[database] => aaldev
[username] => root
[password] =>
[host] => localhost
[port] =>
[driver] => mysql
[prefix] => Array
(
[default] =>
)
)
[schema:protected] =>
[prefixes:protected] => Array
(
[default] =>
)
[prefixSearch:protected] => Array
(
[0] => {
[1] => }
)
[prefixReplace:protected] => Array
(
[0] =>
[1] =>
)
)
[queryString] => SELECT uid, name, status, created, access FROM users u WHERE uid <> 0 LIMIT 50 OFFSET 0
)
Please help me on this.

Assuming that your query is correct, and Drupal documentation, you have a fetchAll() method:
$data = db_query("SELECT uid, name, status, created, access FROM {users} u WHERE uid <> 0 LIMIT 50 OFFSET 0");
$data->fetchAll();
Retrieve all records into an indexed array of stdClass objects.

Related

How to get the data Using Yii2 Query Builder

What i am trying
I have 2 table staff and salarydetails,i want to fetch staff name and there respective salary
$salaries = SalaryDetails::find()->select('salary_details.total_salary AS salary,staff.name AS name')
->leftJoin("staff",'salary_details.staff_id = staff.id');
if ($fcreated_date != null && $tcreated_date != null) {
$salaries->andFilterWhere(['>=','salary_details.salary_given_date', $fcreated_date]);
$salaries->andFilterWhere(['<=', 'salary_details.salary_given_date', $tcreated_date]);
}
when i try to print sql raw query by using
echo $salaries->createCommand()->getRawsql();
i got SELECT salary_details.total_salary AS salary, staff.name AS name FROM salary_details LEFT JOIN staff ON salary_details.staff_id = staff.id
and this query gives the data i wanted in phpMyadmin
But the array gives ie, print_r($salaries); gives
yii\db\ActiveQuery Object ( [sql] => [on] => [joinWith] => [select] => Array ( [0] => salary_details.total_salary AS salary [1] => staff.name AS name ) [selectOption] => [distinct] => [from] => [groupBy] => [join] => Array ( [0] => Array ( [0] => LEFT JOIN [1] => staff [2] => salary_details.staff_id = staff.id ) ) [having] => [union] => [params] => Array ( ) [_events:yii\base\Component:private] => Array ( ) [_behaviors:yii\base\Component:private] => Array ( ) [where] => [limit] => [offset] => [orderBy] => [indexBy] => [modelClass] => common\models\SalaryDetails [with] => [asArray] => [multiple] => [primaryModel] => [link] => [via] => [inverseOf] => )
Thanks,
As you can see in your print_r, $salaries is an ActiveQuery instance. Call the methods ->asArray()->all() on it to get the records.
$query = SalaryDetails::find()
->select('salary_details.total_salary AS salary,staff.name AS name')
->leftJoin("staff",'salary_details.staff_id = staff.id');
if ($fcreated_date != null && $tcreated_date != null) {
$query->andFilterWhere(['>=','salary_details.salary_given_date', $fcreated_date]);
$query->andFilterWhere(['<=', 'salary_details.salary_given_date', $tcreated_date]);
}
$salaries = $query->asArray()->all();
Note that without asArray the all would return an array of SalaryDetails records and you would loss the staff name.

How to get the same result array when querying laravel table

When using laravel built in laravel model methods returns a list of result array. But when querying the same table getting different object. Please check the below code - how can I get the same result set?
$users = User::all();
Illuminate\Support\Collection Object
(
[items:protected] => Array
(
[0] => stdClass Object
(
[id] => 10
[email] => amirtha#gmail.com
)
[1] => stdClass Object
(
[id] => 12
[email] => renjith#123.com
)
)
But when using the sql query like the below:
$result = DB::table('users as u')
->select('u.id','u.email','u.role','u.created_at')
->join('roles as r','r.id','=','u.role')
->where('u.role', '!=', 1 )
->orderBy('u.name','asc')
->get();
print_r($result);
I get:
Illuminate\Database\Eloquent\Collection Object
(
[items:protected] => Array
(
[0] => App\User Object
(
[fillable:protected] => Array
(
[0] => name
[1] => email
[2] => password
[3] => lastname
[4] => mobile
[5] => role
)
[hidden:protected] => Array
(
[0] => password
[1] => remember_token
)
[casts:protected] => Array
(
[email_verified_at] => datetime
)
[connection:protected] => mysql
[table:protected] => users
[primaryKey:protected] => id
[keyType:protected] => int
[incrementing] => 1
[with:protected] => Array
(
)
[withCount:protected] => Array
(
)
[perPage:protected] => 15
[exists] => 1
[wasRecentlyCreated] =>
[attributes:protected] => Array
(
[id] => 1
[name] => amritha
[email] => amritha#gmail.com
)
I think your problem is when you want to use the table alias so what about this:
$result = User::query()->from('User as u')
->select('u.id','u.email','u.role','u.created_at')
->join('roles as r','r.id','=','u.role')
->where('u.role', '!=', 1 )
->orderBy('u.name','asc')
->get();
.
This query is the same with "SELECT * FROM USERS"
$users = User::all();
While this one is different from the earlier query
$result = DB::table('users as u')
->select('u.id','u.email','u.role','u.created_at')
->join('roles as r','r.id','=','u.role')
->where('u.role', '!=', 1 )
->orderBy('u.name','asc')
->get();
print_r($result);

Sorting in Elastic Search by defined type

I have this request to elastic service.
Url callback is:
GET
/es-main/Project,ProjectStage,Task,TaskComment,TicketComment,Client,User,Attachment/_search
How to add Sort improvement requirements that the results were in sequence as they are embedded in the URL + score? Now alphabetically by type. Example first is type Project, second is ProjectStage, etc...
Thanks all for answers...
GET /es-main/Project,ProjectStage,Task,TaskComment,TicketComment,Client,User,Attachment/_search
Array
(
[query] => Array
(
[query_string] => Array
(
[query] => *a*
[analyzer] => hunspell_cs
[fields] => Array
(
[0] => name
[1] => description
[2] => tags.name
[3] => text
[4] => email
[5] => filename
)
)
)
[from] => 0
[size] => 10
[sort] => Array
(
[_type] => ASC
[_score] => DESC
)
[aggs] => Array
(
[CountByType] => Array
(
[terms] => Array
(
[field] => _type
)
)
)
)
Okey, i have added in document _is_Project = 1, _is_ProjectStage = ,_is_Task = 1, etc...
and set ordering to:
order: {
'_is_Project': {'unmapped_type': 'long'}, // first
'_is_ProjectStage': {'unmapped_type': 'long'}, // second
'_is_Task': {'unmapped_type': 'long'}, // third - etc...
'_score': 'DESC'
}

Echo return values from rows from db

Does it make difference to get the value of result set when using alias names and join in the SQL generated using zend framwork.
Regarding to the sql resulted from the selected answer in this question I want to print all result in .phtml file.
I make like this
<?php
foreach($this->rows as $row){
echo $row->visit_id . ' ' . $row->rep_id . ' '.$row->target;
?>
When I print the size of $this->rows it returns the correct number of rows, but it doesn't print any thing?!
Edit
here's what I get when I print $rows
Zend_Db_Statement_Pdo Object ( [_fetchMode:protected] => 2 [_stmt:protected] => PDOStatement Object ( [queryString] => SELECT `r`.`rep_id`, `r`.`visit_id`, `v`.`target`, `v`.`visit_id` FROM `visit_report_tb` AS `r` INNER JOIN `inspection_visits_tb` AS `v` ON v.visit_id=r.visit_id WHERE (r.visit_id = 1) ) [_adapter:protected] => Zend_Db_Adapter_Pdo_Mysql Object ( [_pdoType:protected] => mysql [_numericDataTypes:protected] => Array ( [0] => 0 [1] => 1 [2] => 2 [INT] => 0 [INTEGER] => 0 [MEDIUMINT] => 0 [SMALLINT] => 0 [TINYINT] => 0 [BIGINT] => 1 [SERIAL] => 1 [DEC] => 2 [DECIMAL] => 2 [DOUBLE] => 2 [DOUBLE PRECISION] => 2 [FIXED] => 2 [FLOAT] => 2 ) [_defaultStmtClass:protected] => Zend_Db_Statement_Pdo [_config:protected] => Array ( [dbname] => inspection [username] => root [password] => 123456 [charset] => [persistent] => [options] => Array ( [caseFolding] => 0 [autoQuoteIdentifiers] => 1 [fetchMode] => 2 ) [driver_options] => Array ( ) ) [_fetchMode:protected] => 2 [_profiler:protected] => Zend_Db_Profiler Object ( [_queryProfiles:protected] => Array ( ) [_enabled:protected] => [_filterElapsedSecs:protected] => [_filterTypes:protected] => ) [_defaultProfilerClass:protected] => Zend_Db_Profiler [_connection:protected] => PDO Object ( ) [_caseFolding:protected] => 0 [_autoQuoteIdentifiers:protected] => 1 [_allowSerialization:protected] => 1 [_autoReconnectOnUnserialize:protected] => ) [_attribute:protected] => Array ( ) [_bindColumn:protected] => Array ( ) [_bindParam:protected] => Array ( ) [_sqlSplit:protected] => Array ( [0] => SELECT `r`.`rep_id`, `r`.`visit_id`, `v`.`target`, `v`.`visit_id` FROM `visit_report_tb` AS `r` INNER JOIN `inspection_visits_tb` AS `v` ON v.visit_id=r.visit_id WHERE (r.visit_id = 1) ) [_sqlParam:protected] => Array ( [0] => SELECT `r`.`rep_id`, `r`.`visit_id`, `v`.`target`, `v`.`visit_id` FROM `visit_report_tb` AS `r` INNER JOIN `inspection_visits_tb` AS `v` ON v.visit_id=r.visit_id WHERE (r.visit_id = 1) ) [_queryId:protected] => )
If you are using the query you accepted in the other question, your field names should be as you expect.
I usually just var_dump $row to see what's there is what I expect:
<?php
foreach($this->rows as $row){
//Zend_Debug::dump() provides formatted debug info, the second argument is a label
Zend_Debug::dump($row, 'Row')
?>
This should give you a pretty good idea of what each row contains with out all the baggage that $rows has.
Heh, and that's why I pointed You to ReferenceMap i Zend_Db_Tables. Check my answer to Your previous question.
https://stackoverflow.com/a/9905206/1278879
Using my code from Your previous question You could've done it like this:
foreach ($reportRowset as $reportRow) {
echo $reportRow->visit_id . ' ' . $reportRow->rep_id . ' '.$visitRow->target;
}
And that's piece of cake
The row is not an object, its an array and it can be get like this:
print $row['rep_id']

Filter Facebook Stream by Post privacy?

i query some wall data within my facebook tab.
I was wondering how to filter the data (query) to show only post which are visible to a certain country.
$query = " SELECT
post_id, created_time, attachment,action_links, privacy
FROM
stream
WHERE
source_id = ".$page_id."
AND viewer_id = ".$user_id."
AND actor_id = ".$actor_id."
LIMIT
50";
The Output already show Australia: But how to filter for Australia-Only.
Array (
[posts] => Array
(
[0] => Array
(
[post_id] => 123
[viewer_id] => 123
[source_id] => 123
[type] => 46
[app_id] =>
[attribution] =>
[actor_id] => 123
[target_id] =>
[message] => Only for Austria
[attachment] => Array
(
[description] =>
)
[app_data] =>
[action_links] =>
[comments] => Array
(
[can_remove] => 1
[can_post] => 1
[count] => 0
[comment_list] =>
)
[likes] => Array
(
[href] => http://www.facebook.com/social_graph.php?node_id=118229678189906&class=LikeManager
[count] => 0
[sample] =>
[friends] =>
[user_likes] => 0
[can_like] => 1
)
[privacy] => Array
(
[description] => Austria
[value] => CUSTOM
[friends] =>
[networks] =>
[allow] =>
[deny] =>
)
[updated_time] => 1271520716
[created_time] => 1271520716
[tagged_ids] =>
[is_hidden] => 0
[filter_key] =>
[permalink] => http://www.facebook.com/pages/
)
I think you'll have to add another filter to the query:
$query = " SELECT
post_id, created_time, attachment,action_links, privacy
FROM
stream
WHERE
source_id = ".$page_id."
AND viewer_id = ".$user_id."
AND actor_id = ".$actor_id."
AND privacy = ".$your_privacy_filter // Austria, in this case.
LIMIT
50";
Maybe the filter has to be like this:
//...
"AND privacy.description = ".$your_privacy_filter

Categories