Trying to get the property of non-object in yii - mysql

Firstly i wanna create query for join in yii..
$data = Yii::app()->db->createCommand()
->select('u.mobile,p.mobile')
->from('profile p')
->join('users u','p.name=u.username')
->queryAll();
and i wanna show the retrieved data in view as
foreach ($data as $show){
echo $show->mobile;}
but data is not displaying and shows error as Trying to get property of non-object ..
please help any suggestions

Method queryAll() will return a set of rows. each row is an associative array of column names and values. Try access as array.
Example:
foreach ($data as $show){
echo $show[Your Key]
}

Related

DB Query on returning one value Laravel

Im using a simple query to pull the users in a table called users.
$users = DB::table('users')->get();
Then using a foreach loop to get the values , for example :
foreach ($users as $user)
{
return $user->email;
}
There is definitely 2 records in the DB Table, but it only returns one line. If i try to query a different table it does the same thing.
If i use the Query Log between the query
DB::enableQueryLog();
$users = DB::table('users')->get();
$result = DB::getQueryLog();
It returns the query and it looks fine
[{"query":"select * from `users`","bindings":[],"time":0.85}]
This table was created within PhpMyAdmin and not using the Artisan Migrate
Of course it so, cause you return from loop, use echo
foreach ($users as $user)
{
echo $user->email;
}
return statement inside the loop will behave like break for your case, this means breaking the loop.
You can use either:
DB::table('users')->select(['email'])->get();
or
DB::table('users')->get(['email']);
But its basics, you can easily find this stuff in docs https://laravel.com/docs/master/

mySQL query for building dynamically populated model

I have some code below which demonstrates a hard-coded example of what I would like to accomplish dynamically.
At a high level, I wish to do something like select * from view_data_$app_state and then get all of the data from that views table into my mustache templates dynamically.
The code I currently must use to group multiple rows of data for a specific column along with the views data is:
<?php
error_reporting(E_ALL);
class Example {
function __construct(){
try {
$this->db = new PDO('mysql:host=localhost;dbname=Example', 'root','drowssap');
}
catch (PDOException $e) {
print($e->getMessage());
die();
}
}
function __destruct(){
$this->db = null;
}
function string_to_array($links_string){
return explode(",", $links_string);
}
function get_view_data(){
$q = $this->db->prepare('select *, GROUP_CONCAT(`links`) as "links" from `view_data_global` ');
$q->execute();
$result = $q->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
}
$Example = new Example();
$result = $Example->get_view_data();
$result[0]["links"] = $Example->string_to_array($result[0]["links"]);
echo json_encode($result);
This gives me the perfect object while
GROUP_CONCAT seems to be doing the trick this way, however I MUST know the column name that will contain multiple rows before writing the query. I am trying to figure out an approach for this and wish to make a custom query + code example that will transform cols with multiple rows of null null and not empty data into an array like above - but return the data.. again like the code above.
Below is an output of the actual data:
[{"id":"1","title":"This is the title test","links":["main","about","store"]}];
How can I replicate this process dynamically on each view table?
Thank you so much SO!
You can use PDOStatement::fetch to retrieve your results, with fetch_style set to PDO::FETCH_ASSOC (some other values will also provide the same information). In this case, the result set will be array indexed by column name. You can access this information with foreach (array_expression as $key => $value)
See the documentation for additional information.

Retrieve every model and return three values

I am looking for a way to retrieve all models in a database. Then loop through all of the models and read out the values for name, firstname and phonenumber.
So far I've gotten this and failed to go past it:
$searchModel = new EmployeeSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
I am then looking to implement those three values in a simple HTML table:
<tr><td>$firstname</td><td>$name</td><td>$phone</td></tr>
The table should be part of a PDF output, so ideally I would save it to a variable:
$html_table = '<tr><td>$firstname</td><td>$name</td><td>$phone</td></tr>';
I would need to get this for every model that fulfills the criteria of status = 'active' in the database.
So far I've only been able to get tables via gridView and not in a HTML template either.
You don't really need a data provider to achieve this, you could simply try :
$models = Employee::find()->where(['status'=>'active'])->orderBy('name ASC')->all();
foreach ($models as $model) {
echo "<tr><td>{$model->firstname}</td><td>{$model->name}</td><td>{$model->phone}</td></tr>";
}
Read more : http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#querying-data
You can get all models like this:
$employees = Employee::find()
->select('firstname, name, phone')
->asArray()
->where(['status'=>'active'])
->all();
This way you will get an array of arrays containing the 3 selected fields, so now you only need to use a foreach to loop through them and create the table:
$html = '<table>';
foreach($employees as $employee) {
$html .= '<tr><td>'.$employee['firstname'].'</td><td>'.$employee['name'].'</td><td>'.$employee['phone'].'</td></tr>';
}
$html .= '</table>'

How to get array format data from json data in laravel4 query builder?

I am using laravel4 query builder . I have following query which returns json data .
$query=DB::connection('mysqlMagento')->
table('magento_catalog_category_flat_store_1')->
join('sohyper_region_activity', 'magento_catalog_category_flat_store_1.entity_id', '=', 'sohyper_region_activity.activity_id')->
select("magento_catalog_category_flat_store_1.entity_id" , "magento_catalog_category_flat_store_1.parent_id" , "magento_catalog_category_flat_store_1.name as label" ,"magento_catalog_category_flat_store_1.url_key as name")->
get();
The above query returns json format data , I want to convert this to arrat format . I know Toarray() is used in eloquent to convert this but here it is in query builder , please help me on this .
Thanks.
$query=DB::connection('mysqlMagento')->
table('magento_catalog_category_flat_store_1')->
join('sohyper_region_activity', 'magento_catalog_category_flat_store_1.entity_id', '=', 'sohyper_region_activity.activity_id')->
select("magento_catalog_category_flat_store_1.entity_id" , "magento_catalog_category_flat_store_1.parent_id" , "magento_catalog_category_flat_store_1.name as label" ,"magento_catalog_category_flat_store_1.url_key as name")->
get();
$array = json_decode($query);
Though i'm fairly sure that the query builder is not returning JSON.
The query builder returns an array of objects. For example the query:
$users = DB::table('users')->select('name')->get();
will return an array which you can handle like this
foreach($users as $user) {
echo $user->name;
}
EDIT
If you want to convert it to array you have to do it on your own.
Here is a quick way
$users = json_decode(json_encode($users), true);
Now you can handle it like this
foreach($users as $user) {
echo $user['name'];
}

Codeigniter - Perform action if database query returns no results

How can I return a value of 'no data found' if my query returns no results???
This is my code:
function getTerms($letter) {
$this->db->select('term, definition');
$this->db->from('glossary');
$this->db->where(array('letter' => $letter));
$query = $this->db->get();
foreach ($query->result() as $row) {
$data[] = array(
'term' => $row->term,
'definition' => $row->definition
);
}
return $data;
}
It currently returns the $data variable even if the query returns no results which is giving me php errors. How can I check that there are results before returning the $data array.
Simply check that the query returns at least one row:
if ($query->num_rows() > 0) {
// query returned results
} else {
// query returned no results
}
Read more in the docs
It currently returns the $data variable even if the query returns no results which is giving me php errors.
It's a good habit to initialize the array that you intend to build:
$data = array();
// Loop through possible results, adding to $data
If there are no results you'll get an empty array returned, then check that in your controller.
This way, at least the variable is defined and you won't get notices.
What about to give initial empty array value for $data
Just put
$data = array();
before foreach
<?php
return is_array($data) ? $data : array();
}