MySQL query with temporary column's name in Yii - php

I want to select only year from records ane make from this data assoc array
$wynik = $model_post::model() -> findAllBySql('SELECT DISTINCT YEAR(create_time) as rok FROM tbl_post');
for($i;$i<count($wynik);$i++)
{
$rok[$wynik[$i]->rok]=$wynik[$i]->rok;
}
but I got the exception
_Property "Post.rok" is not defined._
How can I make it correct?

If I remember correctly this should work in Yii1 as well: define a variable public $rok; in your model_post class, and it will automatically be populated when you use that query.

Related

Laravel mySQL view return by specific ID

So I am quite new to Laravel, and I have a situation, where I am trying to gather data from a pivot table (contains 2 foreign keys only) in order to retrieve data from other tables.
Before everything, I'd like to note, that word "campaign" is the same as "box". Simply it differs in database and front.
I have multiple boxes, that contains specific gifts.
I have set the URL of the box to be something as such: http://127.0.0.1:8000/box/1
http://127.0.0.1:8000/box/2
etc..
I have done so, by simply using a button with the {id}:
View the box
My plan is, to print out only that specific boxes gifts (right now, all boxes print out all gifts).
I have tried to use the ->where option within my function, although, it seems that I can't try equaling to the campaigns ID.
Incorrect code:
function box(){
$data = array(
'list'=>DB::table('campaigns_gifts')
->join('gift_items', 'gift_items.id', '=', 'campaigns_gifts.gift_foreignK')
->select('gift_items.*')
->where($campaign_foreignK = '{id}')
->get()
);
return view('DBqueries.boxView', $data);
}
My question is, how can I specifically return data, that only belongs to that specific box, since I am not able to use mysql where option.
For reference, these are the database tables:
Basically, I would need to match my URL's id with campaign_foreignK
Thank you in advance.
First of all, yout need to start to use Laravel Eloquent Models.
But doing by your way (the hardest):
You need to create a route in web or api, something like that:
Route::get('/box/{id}', [BoxController::class, 'view']);
Then you need to put this function on your controller:
function view($id){
/**
* You can do it by 2 ways:
* 1 - Do a where in the result of DB query (the bad way)
*/
$list = DB::table('campaigns_gifts')
->join('gift_items', 'gift_items.id', '=', 'campaigns_gifts.gift_foreignK')
->select('gift_items.*')
->where($campaign_foreignK = '{id}')
->get();
$list = (array)collect($list)->where('abc', 123);
/**
* Or the second way (the best is to use the Eloquent, but using DB the following is the best)
* 1 - Get the relations:
* Is git_items id the key for gift_foreignK ? i'm supposing that is it! so....
*/
$giftsIds = array_values((array)DB::select("select * from campaigns_gifts where campaign_foreignK = $id"));
$giftsIdsString = implode($giftsIds, ',');
$list = (array)DB::select("select * from gift_items where id in ($giftsIdsString)");
return view('DBqueries.boxView', ['list' => $list]);
}

f3 / Fat Free Framework: why does the SQL-Mapper select function return all columns from a table?

Imagine a MySQL table with two columns, col1 and col2, queried by f3's SQL-Mapper like this:
$rows = $mapper->find();
$rows = $mapper->select('col1');
When using find both columns are queried and returned and one can access them like this:
... = $rows[0]->col1;
... = $rows[0]->col2;
When using select calling $rows[0]->col2 will return null, because col2 was not included in the string argument of the select method, which is fine.
Now when doing a var_dump I noticed that the select method returns all columns! Why is this?
I imagined the purpose of the select method would be to save resources on the database server by only querying for the specified columns. So what is the purpose of the SQL-Mapper: select method if it returns the full set of columns – we have the find method for that, don't we?
The purpose of the Fat-Free SQL mapper is to automatically map table columns to PHP object properties. This is done at instantiation time in DB\SQL\Mapper::__construct.
So when you call $mapper->find() or $mapper->select(), the instantiation has already been performed and table columns have already been mapped to the $mapper object.
This explains the results of your var_dump command.
Now you can adjust the list of columns actually mapped, but that has to be done at instantiation:
// map all columns
$mapper = new DB\SQL\Mapper($db,'table_name');
// only map col1 & col2 columns
$mapper = new DB\SQL\Mapper($db,'table_name','col1,col2');
Concerning the select() method, I'm wondering why this method has been made public. It is used internally by find(), but is not very handy to use on its own, considering that all the specified fields have to match declared columns at instantiation and that computed columns should be both aliased AND declared. See:
$mapper = new DB\SQL\Mapper($db,'table_name','col1,col2');
// ex.1: column not declared
$results = $mapper->select('*');
echo $results[0]->col3; // undefined field col3
// ex.2a: computed column not aliased
$results = $mapper->select('SUM(col1)');
echo $results[0]->{'SUM(col1)'}; // undefined field SUM(col1)
// ex.2b: computed column aliased but not declared
$results = $mapper->select('SUM(col1) AS sum1');
echo $results[0]->sum1; // undefined field sum1
// ex.2c: computed column declared but not aliased
$mapper->sum1 = 'SUM(col1)';
$results = $mapper->select('SUM(col1)');
echo $results[0]->sum1; // empty
// ex.2d: computed column aliased and declared
$mapper->sum1 = 'SUM(col1)';
$results = $mapper->select('SUM(col1) AS sum1');
echo $results[0]->sum1; // OK!
As you can see, the usage of this method is very strict. I wouldn't advise to use it, unless you really know what you're doing. Use find() instead.

Codeigniter dynamic table with database query

I want to make a table for the reporting of some data.
So I have a query in my model called:
query($statusId, $regionId);
so the value depends on statusID and regionID.
___________|____1___|____2____|____3___|
|_____1_____|query(1,1)|query(1,2)|query(1,3)|
|_____2_____|query(2,1)|query(2,2)|query(2,3)|
|_____3_____|query(3,1)|query(3,2)|query(3,3)|
But how can I do this?
Here I write the query into the $data array in the controller. But i dont know how to define the $statusId and $regionId
$num_meas_region= $this->MMeasure->get_measure_number_and_region($statusId, $regionId);
$data["num_meas_region"] = $num_meas_region;

fat-free SELECT is not returning any data

i am using Fat-Free Framework to do rapid prototyping of my application. Now, whenever I try to load some data from database, i can use the load() function within the SQL\Mapper but it returned all of the column.
I found SELECT() function but it does not returning any data.
$this->load(['myId=?',$id]) will return the data along with the other columns
$this->select('name',['myId=?',$id]) should return the data from name column but i got nothing.
$this->db->exec('SELECT name FROM persons WHERE myId=?',$id) will return the the data from name column.
what is the proper way of using SELECT() from Fat-Free framework? my goal is to only retrieve single data from name column only.
The right way to do it is like this:
$table = new DB\SQL\Mapper($db, 'persons');
// assign to $results
$results = $table->load(array('myId=?', $id));
foreach($results => $row){
echo $row->name;
}
As described here: https://fatfreeframework.com/3.6/databases#SeekandYouShallFind

How to check if data is already in database using PHP?

Situation:
My PHP script will run once a way.
and that will store data in my database.
Since 1 week is good enough for me, so I only want to keep just that.
Let's say if today is Friday OR 5 (in my case).
Is there a way to check if date == 5 is already exist in the database, and possibly override it with the one ?
If today is Friday/5, then all the old data with date == 5 should be overridden and store the new one instead.
Literally, I only want to store one full week worth of data.
Tomorrow, and the next will repeat the same logic.
Here is how I insert my data into my database :
$data = new Data;
$data->name = $name;
$data->description = $description;
$data->dayOfWeek = $today; // could be 0,1,2,3,4,5,6
$data->save();
I am not sure, how do I accomplish that in Laravel.
Any tip/suggestion will be much appreciated !
Why don't you do this outside of your foreach loop - before you insert
Data::where("dayOfWeek","=", $today )->delete();
That should take care of what you want, then you can continue insert just like normal:
$data = new Data;
$data->name = $name;
$data->description = $description;
$data->dayOfWeek = $today; // could be 0,1,2,3,4,5,6
$data->save();
You can use INSERT ... ON DUPLICATE KEY UPDATE eg. like that
INSERT INTO `data` (`name`, `description`, `day`) VALUES (:name, :description, :day)
ON DUPLICATE KEY UPDATE name = VALUES(name), description = VALUES(description)
Of course you have to declare unique key on day field to make it work.
If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index or PRIMARY KEY, an UPDATE of the old row is performed. For example, if column a is declared as UNIQUE and contains the value 1, the following two statements have identical effect:
Sample Code:
INSERT INTO table (a,b,c) VALUES (4,5,6)
ON DUPLICATE KEY UPDATE c=9;
Firstly get the data from the database;
$data = Data::where('dayOfWeek', $today)->first();
Then check to see if the data is there, if it is update if not create.
if (!is_null($data)){
$data->update($new_attribute_data)
}
else {
Data::create($new_attribute_data);
}
As a note: Using the update method can require you to fill the $fillable array within your model if you putting GET or POST data into it. You can do it like so;
class Data extends Eloquent {
...
protected $fillable = ['name','description','dayOfWeek'];
}
And Laravel will fill the Model Attribute with the corresponding data within the Input.
EDIT:
As a faster way for the above method, use the updateOrCreate method;
Data::updateOrCreate(['dayOfWeek' => $today], $new_attribute_data);
This will search for Data models with attributes that match the first parameters, and will update its other attributes with the second parameter. Ref

Categories