Retrieve every model and return three values - html

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>'

Related

Trying to get the property of non-object in yii

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]
}

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.

Mass update in Laravel Eloquent or DB

Is there anyone who knows how to do this without the technique of doing it in a one query string. I mean the popular ways I see on the net is by looping in data(the updates) and generating a single update statement and then fire a query. Is it possible for an Eloquent Approach or DB without looping?
This is posible with Eloquent, it might be necessary to enable mass-assignment, but you will get an error if so.
$post_data = Input::all();
$model = Model::find($id);
$model ->fill($post_data);
$model ->save();
or
$post_data = Input::all();
Model::find($id)->update($post_data);
Yes, you can do that but in that case, you have to make the array of data that is a loop is needed to store the data in the array with respective field_name => value of the table.
The following is the example:
$Array = array(); //This is needed to hold data while looping over $YourData
$YourData - is the array of data you want to store in the respective table.
foreach ($YourData as $YourDatakey => $YourDatavalue ){
$Array = [
'table_column_name' => $YourDatavalue['value_from_array'],
'table_column_name' => $YourDatavalue['value_from_array'],
'table_column_name' => $YourDatavalue['value_from_array'],
...... and so on
];
}
$InsertQuery= YourModelName::create($Array);
PS:
YourModelName model file should have the columns in protected
$fillable = ['column1','column2'....];
You should use App\Models\ModelName; at the top of the file.

Laravel Select Query within helper file

I'm coming from codeigniter background. Unlike codeigniter helper directory, i just created helper directory within app directory of Laravel. Just want to know how to execute query within this common function. Here is my codeigniter function.
function show_menu($primary_key_col, $parent_id, $sort_order)
{
$output = "";
$ci =& get_instance();
$ci->db->select("*");
$ci->db->where('is_active', "Y");
$ci->db->where('is_delete', "N");
$ci->db->where('parent_id', $parent_id);
($sort_order!="")?$ci->db->order_by($sort_order, "ASC"):"";
$query = $ci->db->get('tbl_cms_menus');
foreach ($query->result() as $row){
$output .= '<option value="'.$row->$primary_key_col.'">'.$indent.$row->menu_name.'</option>';
}
return $output;
}
I tried something like this in laravel file. but this code did't give me any result. Please tell me where i'm doing wrong in this code. thanks
function databaseTable()
{
$table = DB::table('tbl_cms_menus');
$get_rows = $table->get();
$count_rows = $table->count();
if($count_rows > 0){
foreach ($get_rows as $tbl)
{
echo $tbl->menu_name;
}
}
}
This code will rot so hard that it shipped pre-rotten.
But, if you want to just.. ram it into the app all dry like that.. then add something like this to your base controller class...
$whatever = crazyChainingStuff;
foreach ($whatever ...) { $topMenu .= ... }
View::share('topMenu', $topMenu);
If you want to learn how to write code that will do less damage to your company and your clients then I recommend starting by watching Uncle Bob's "Fundamentals" videos. At least the first 5-6. http://cleancoders.com
It looks like you are trying to generate a drop-down/select with some data from your database, in this case, you should pass the data required for the drop-down/select from your controller to the view where you have written your HTML, for example, in your view, you may have a select like this:
echo Form::select('cms_menu', $cms_menu, Input::old('cms_menu'));
Or this (If you are using Blade):
{{ Form::select('cms_menu', $cms_menu, Input::old('cms_menu')) }}
From your controller you should pass the $cms_menu which should contain the menu-items as an arrtay and to populate that array you may try something like this:
$menuItems = DB::table('tbl_cms_menus')->lists('menu_name','id');
return View::make('your_view_name', array('cms_menu' => $menuItems));
Also, you may use something like this:
// Assumed you have a Page model
$menuItems = Page::lists('menu_name', 'id');
return View::make('your_view_name', array('cms_menu' => $menuItems));
You may also read this article which is about building a menu from database using view composer (More Laravelish way). Read more about Form::select on documentation.
It was too late to give an answer. I was also from CodeIgniter background and when I learnt Laravel then first I try to find how can I write a query in Helper. My Team leader helped me.
I have converted your code in a helper function.
function show_menu($primary_key_col, $parent_id, $sort_order)
{
$query = DB::table('tbl_cms_menus')
->select('*')
->where('is_active', '=', 'Y')
->where('is_delete', '=', 'N')
->where('parent_id', '=', $parent_id);
($sort_order != "")? $query->orderBy($sort_order, "ASC") : "";
$resultData = $query->get()->toArray();
}
Here $resultData will be array format. Now, you can create a foreach loop according to your requirement.

PHP PDO succinct mySQL SELECT object

Using PDO I have built a succinct object for retrieving rows from a database as a PHP object with the first column value being the name and the second column value being the desired value.
$sql = "SELECT * FROM `site`"; $site = array();
foreach($sodb->query($sql) as $sitefield){
$site[$sitefield['name']] = $sitefield['value'];
}
I now want to apply it to a function with 2 parameters, the first containing the table and the second containing any where clauses to then produce the same result.
function select($table,$condition){
$sql = "SELECT * FROM `$table`";
if($condition){
$sql .= " WHERE $condition";
}
foreach($sodb->query($sql) as $field){
return $table[$field['name']] = $field['value'];
}
}
The idea that this could be called something like this:
<?php select("options","class = 'apples'");?>
and then be used on page in the same format as the first method.
<?php echo $option['green'];?>
Giving me the value of the column named value that is in the same row as the value called 'green' in the column named field.
The problem of course is that the function will not return the foreach data like that. That is that this bit:
foreach($sodb->query($sql) as $field){
return $table[$field['name']] = $field['value'];
}
cannot return data like that.
Is there a way to make it?
Well, this:
$sql = "SELECT * FROM `site`"; $site = array();
foreach($sodb->query($sql) as $sitefield){
$site[$sitefield['name']] = $sitefield['value'];
}
Can easily become this:
$sql = "SELECT * FROM `site`";
$site = array();
foreach( $sodb->query($sql) as $row )
{
$site[] = $row;
}
print_r($site);
// or, where 0 is the index you want, etc.
echo $site[0]['name'];
So, you should be able to get a map of all of your columns into the multidimensional array $site.
Also, don't forget to sanitize your inputs before you dump them right into that query. One of the benefits of PDO is using placeholders to protect yourself from malicious users.