save formula in database and substitue value at runtime php - php

i want to store the following formula in database
Z-Score = 1.2(Working_Capital/Total_Assets) + 1.4(Market_Value/Total_Assets)
Working_Capital,Total_Assets,Retained_Earnings are stored in database against different tables
eg:- Total_Assets = BalanceSheet.totalAssets, Market_Value = expert.market_value
this formula can be changed by the user through a form, he can add more quantities to the formula
Z-Score = 1.2(Working_Capital/Total_Assets) + 1.4(Market_Value/Total_Assets)+1.0(Sales/Total Assets)
PROBLEM:-
now keeping in mind that the formula can change anytime i need to store this in the database accross the user id so that i can give it an edit option.
also the formula is used to calculate data over period of years.
many users will have many formula.
APPROACH:-
from what i read so far many suggest to store it as a string, it is not possible since the values i need to display the user for editing the formula is different than what it is in database.
some suggest to convert the expression to tree data structure but i don't know which tree structure will suit my application???
lastly i need to store it in mysql database so will tree storing and retrieving be faster???
i am asking for suggestions as i feel its a complex problem but if anyone have already solved it PHP then please feel free to share
thanks in advance.

Solution to the above approach that i came up with.
1) take the formula from the user and when he is selecting the formula operands create a new array of operands which maps the names of operands in frontend with they corresponding values of database table and colunm name
eg:-
`$input['operands'] = array(
array('Total_Assets' => 'balance_sheet.TotalAssets'),
array('Working_Capital' => 'balance_sheet.WorkingCapital'),
array('Revenue' => 'balance_sheet.TotalRevenue'),
);`
2) create an infix form of the formula from which you can create a binary tree of the following form
infix form:-
(
[0] => revenue
[1] => total_assets
[2] => working_capital
[3] => +
[4] => /
)
Binay tree:-
{"__exp1":{"operator":"+","operand":["working_capital","total_assets"]},"root":{"operator":"\/","operand":["__exp1","revenue"]}}
3) now send all this to the server and there i save it as each column of table, also reverse mapping of the tree to infix form of the formula is possible on server side
4) this helps me to substitute the database values since i have the database column array from which i get the values and execute the formula and return the values.

Related

PHP MYSQL link array with uuid Json

First of all, I'm happy to see people helping people here :D.
I got also a small issue sadly,
DB 1 contains:
UUID and much values.
DB 2 contains:
UUID and again many other values.
what I want is
[0] => Array
(
[UUID] => 96
[DB1 values]
[DB2 values]
)
i thought that will work with array_combine but that isn't true sadly because then i miss some db1 values
here database images:
--EDIT--
Your picture helped. You can handle that at the SQL Level
SELECT Login.*, Location.*
FROM Login
LEFT JOIN Location ON Login.UUID=Location.UUID
GROUP BY Login.UUID
Then the resulting data in PHP will already be correctly formatted.
Notice that I chose table Login to drive the query, could have also chosen the Location table. depends on the underlying structure

Mysql performances: serialize vs columns

Let's say that I have array like the one I posted below and that I need to store it in my MySQL database:
Array(
"Weight" => "10",
"Height" => "17",
"Usage" => "35"
);
Preamble:
I will never update these values
I will never perform a query based on these values
Long story short I only need to store and display this array as it is. Actually I need to use these values to generate graphs. Now I see 2 possible options.
Option 1: even if I will never use a WHERE, ORDER BY, HAVING (...) condition on these values, I store each value separately in a dedicated column (weight, height, usage).
Option 2: I create a single column (stats) where I store a serialized version of the array then, in order generate my graphs, I unserialize each row before using it.
The question is: what's the best approach to store this array in terms of effectiveness and performaces?
In my opinion the second approach is the best but let's say that there are many rows and elements involved in the process. I don't understand if it's faster and ligher to unserialize an array made by 20 elements for 100 rows with PHP or to read plain values stored in 20 columns considering that I need to save lot of them very frequently and simultaneously.
I will never update these values
I will never perform a query based on these values
The second you finalise your code having stored them as serialised values, you'll be asked to perform a query to update anything with a weight above ten.
Just store them in their own columns - not only will this future-proof the code, but it is easier to work with and will take up less drive space in the long run.

SQL Database approach - I need your suggestion

Hello everyone and thank you for viewing this question.
Since someone asked what i am doing this for, here is the answer:
An artist asked me to make him a web app to store all his new concerts etc.. Now, when it comes to add the Instruments, artists etc, i could have 10 instruments, or maybe 100.. Everything is set into a form.. Some data is fixed like location, time etc, but this other fields are added dynamically using DOM..
I am building a system in which the user set up a form to be stored on a database like:
Name,Surname,field_1
//Lets say that this is the "fixed" part of the form
//But the user should be able to add 'n' other fields with no limit
//Therefore my problem is that i would end up with a row made of, lets say,
//4 colums
//And another one of, maybe, 100 columns
//
//Then i will need to access these rows, and row one should have 4 cols, row two 100..
//This can't be done in a "traditional" way since each row should have the
//same amount of cols
//
//I thought to create a new table for each submission
//but this doesn't really make that much sense to me..
//
//Storing all the possible fields in a single one and then
//access them through an array ? That would require too much, even since my fields
//should have the possibility to be edited..
//Each field is a mixture of variables then, like
//field1:a=12,field2:b=18.. too complex
Any help would be very appreciated
I would go the one field approach. You could have three columns, Name, Surname, and field_values. In the field_values column, store a PHP serialized string of an array representing what would otherwise be your columns. For example, running:
array(
['col1'] => 'val',
['col2'] => 'val1',
['col3'] => 'val2',
['col4'] => 'val3'
)
through serialize() would give you:
a:4:{s:4:"col1";s:3:"val";s:4:"col2";s:4:"val1";s:4:"col3";s:4:"val2";s:4:"col4";s:4:"val3";}
and you can take this value and run it back through unserialize() to restore your array and use it however you need to. Loading/saving data within this array is no more difficult than changing values in the array before serializing it and then saving it to the field_values column.
With this method you can have as many or few 'columns' as you need with no need for a ton of columns or tables.
In this case I would personally create a new table for each user, with new row inserted for ever new custom field. You must have a master table containing table names of each user table to access the data within later.

Storing multiple GPS coordinates in MySQL

I'm making an Android app that tracks a user and displays their location in real time. I have it working, but I'm having issues storing the coordinates in a database properly. Right now, the user's location will update every second, and it stores the location in a database and then the web app pulls the most recent from the database. I want to be able to store the list of locations in one row for a particular user. I read some about GeoSpatial information in MySQL, and I think that the linestring datatype would work, but I can't seem to find enough information about how to implement the query in PHP. Can someone provide an example of how to keep appending coordinates to the database in a linestring type using PHP? Or provide a suggestion of how to continually store coordinates using one row of a database.
Thanks
Simply store each point the user is located at into a table, along with an ID and timestamp. You can then assemble the points with a query.
Don't store an entire track in one row, or you won't be able to do much with the data later.
Edit: Here is what your table will look like:
gps_points
id (bigint)
user_id (int)
timestamp (timestamp or datetime, depending on your needs)
lat (double)
lon (double)
A GPS coordinate is a set of X,Y and Z float value, not a set of points to interpolate a curve (which essentially is what the linestring datatype is for). So I would store the points in 3 float columns with the additional information like a timestamp. If you need, you can extrapolate the linestring afterwards from the given data to show on a map.
Or you can just simply use Firebase for your database which is very flexible and you can easily work in firebase
My experience is that the UTM format is easier to store in a database since its orthogonal and has a really convenient syntax. And it is suitable for single line string too. You can find information and a handy class that easily converts between GPS and UTM here:
http://www.ibm.com/developerworks/java/library/j-coordconvert/index.html

Assigning database entries to web service entries

Here's the scenario:
I receive a JSON object comprising 140 events. Each event is one of six possible types and includes several details, except for 2 (description and contact name).
I have a MySQL database of the 6 descriptions and contact names.
How can I "attach" the correct description and contact name from the database to each JSON entry in PHP?
I could do a query of the database for each of the events, but this seems needlessly complex and I imagine it would severely slow performance. The best option would be for the provider of the web service to include our descriptions and contact names, but they won't do that.
Thanks in advance.
If you can identify which of the 6 descriptions/contact names you want for each event, then instead of getting them from the database for each event, select them all first then do the lookup in PHP.
For example:
// Build and array like this from your database first
$my_data = array('type1' => array('desc' => 'foo', 'cname' => 'bar'));
for($i=0; $i < count($all_events); $i++){
if(isset($my_data[$all_events[$i]['type']]){
array_merge($all_events[$i], $my_data[$all_events[$i]['type']]);
}
}
I've made some assumptions here, but you should get the general idea. Note you need to do a for loop not and foreach if you want to modify the $all_events array as you go.

Categories