Format data being read in by CakePHP read() function - php

I am using CakePHP to display an input field that has a "price" variable in it upon editing. Coming from the database this number has a 5 decimal points (for complex calculations).
Without setting the column in the database to be set to only float to 2 points, how would I go about converting this variable to float to only 2 points?
<?php echo $form->input('price'); ?>
Please let me know if you need any further information from me.

Did you specify a model when you did your $form->create('Model');
You should be able to manipulate the $this->data by specifying the Model and field.
<?php echo $form->text('price',
array('value' => round($this->data['Model']['price'], 2)));

Related

Laravel eloquent model model attribute casting (Which attribute types should I cast?)

I am not sure I fully understand Laravel Eloquent attribute casting. According to documentation, (https://laravel.com/docs/8.x/eloquent-mutators#attribute-casting), these are the supported types:
integer, real, float, double, decimal:, string, boolean, object, array, collection, date, datetime, timestamp, encrypted, encrypted:object, encrypted:array, and encrypted:collection
So far, I've only used date casting on my models (when the fields were stored as timestamps in the db), like this:
protected $dates = [
'modified_at', 'published_at'
];
I also understand the need for attribute casting to boolean when the values are stored as integers (0 or sth else).
But what about other attribute types (integers, for example), should I always do attribute casting? Or just when the field in the database is of a different type? What are the use cases or what is the best practice with other attributes?
(I can't, for example, imagine creating a string field in migrations, then saving some number inside it as string and then casting it back into an integer on the model?)
By default, attributes will be casted to the type of column defined in the table. So, if your column is an integer, then it will be casted as int.
But, what happens if you want to modify this behavior for specific fields? That's when attribute casting enters the scene.
For example, imagine we have in a table called projects a column named config of type json in which we can store additional configuration elements for each project.
In my case, it'd be useful to be able to handle this data as an array. So, instead of receiving a string or object, we can just deal with a simple array. To do this, we just:
class Project extends Model
{
// ...
protected $casts = [
'config' => 'array',
];
// ...
}
This way, whenever we use Eloquent to fetch projects from the database, each record will have that property as an array. And also, it will be converted back to json when trying to store/update records.
Related to the case you specified (saving element as a string but then retrieve it as an integer) is totally possible of course. You'll need to set both the accessor and the mutator for that field. For an attribute named number:
/**
* This will be called when fetching the element.
*/
public function getNumberAttribute($value)
{
return (int)$value;
}
/**
* This will be called when storing/updating the element.
*/
public function setFirstNameAttribute($value)
{
$this->attributes['number'] = (string)$value;
}
Now, a reason to ever need to make this? Well, you could be dealing with a database not properly well designed, or with a production database that is being used by multiple systems and changes in the db are hard to accomplish. In those cases you could make use of this kind of value manipulation to work as you want in your app.

Stored ENUM is displayed as a string

I have an ENUM stored in PHPMYADMIN which allows the numbers 1-10.
I'm trying to find out how that number can be converted to a string which the user can see, an example is;
1=London
2=Spain
3=France
4=Germany
etc...
The obvious way would be to do an if statement for each something like
if ENUM == 1 then STRING == "London"
if ENUM == 2 then STRING == "Spain"
but I was wondering if there was a similar way of doing this or if I just need to do 10 if statements. I've tried to look online but no helpful tutorials.
Thanks (Sorry i've had to submit the question as code, stackoverflow wouldnt allow me to post it otherwise for some reason)
Here is an efficient/clean/professional way of doing it:
$enum = 1; // The value fetched from the database
$cities = array(
'1'=>'London',
'2'=>'Spain',
'3'=>'France',
'4'=>'Germany'
); // Array of cities
// Make sure there is a city with the given key
if(isset($cities[$enum])){
echo $cities[$enum];
}
But it is also advisable to store the cities in another database table.

How to store data in db in array form

i want to store my PHP values in db(mysql) in the form of array...
for example
$a=array{10,20,30,40};
i want to store this variable $a in to db in the array form like how it's storing in array using index.
why i want to do this because in future i may have to perform update or delete operation on the array values..
i know that it's possible to do this thing... but i don't know how to implement this..
i searched about this topic but i didn't get proper answer....
Please suggest me how to do this things...
Why don't use json_encode in PHP and store it on your database. It's the best way.
The array will be converted to a string and will be stored.
Retrieve the data and make use of json_decode and then start working as per your needs.
Example:
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
OUTPUT: {"a":1,"b":2,"c":3,"d":4,"e":5}
You should create a distinct TABLE to store this kind of data.
Consists of 2 columns, corresponding record ID and the actual data.
So, your record will be looks like
rid value
1 10
1 20
1 30
1 40
2 10
2 40
...
this way you will be able to perform update or delete operation on the array values using conventional SQL routines, as well as selecting data based on the array values.
This is how the things done oin the real world, not in PHP sandbox.
All othe answers here are plainly wrong
I would use serialize/unserialize for this. You can use it like this:
Send to MySQL
<?php
$a = array{10,20,30,40};
$a = serialize($a);
// your code here to send it to the mysql
?>
Get from MySQL
<?php
// your code here to collect it from mysql
$a = unserialize($mysql->str);
?>
The field in the MySQL should be TEXT or VARCHAR.
Regards
BlackBonjour
You can always serialize your array then store the result in a VARCHAR or TEXT field and after fetching you can unserialize the field.

converting floating numbers in php

I have a value in the database of type 'decimal(18,2)' , it has values like 2.50, 1.25 etc.. for some reason when i pull it in, it is not displayedm but all the other values of my table are.. I assume it is because I need some kind of conversion.. but not sure how to
$_price = $row["_price"]; //suppose to pull in 2.50 for example
but comes in blank when i try to print it
print($_price_label.' '.$_price);
Comes out something like this 'The value is $' but the price is not pulled in..
Any ideas how I can achieve this?
Thank you
You don't need to convert it, your variable is not set, or it is 0.
Check your variable names, keys, and column names.
If your column name is "price" you should be using $_price = $row["price"]; (no underscore).

PHP Form Posting Values To Database

Basically, i have a working form where the user inputs details about their laptop to sell to my shop.
I give them a quote once they have submitted the Specs of the laptop.
At the moment i have got option boxes and checkboxes which each have a value-- for example these. ---
<label for="state">State</label><br>
<select name="state">
<option value="10">Excellent</option>
<option value="5">Good</option>
<option value="0">Poor</option>
</select><br>
The Values of the options they have selected get added up at the end and that gives them the quote - in the above example - "10" means £10 extra for a excellent condition laptop etc.
I use $_POST[state] to get the value of it to add onto the other options for the quote.
But my problem lies when i POST them to a database (so we can check when they come in).
When they get added to the database, obviously it just comes out as the values not the actually name of it like "excellent" or "good". just says "10" or "5".
Is there anyway to put the name of the option into the database instead of the value?
sure... just make sure that's what you want to do. It's usually not considered a good database practice to create denormalized tables like that, but you could do it. When you collect your post data, simply create another variable and assign a value to it based off the state value like so:
$stateText = '';
switch ($state){
case 10:
$stateText = 'Excellent';
break;
case 5:
$stateText = 'Good';
break;
case 0:
$stateText = 'Poor';
break;
default:
// bad value
$stateText = '';
}
...then store this to the database in a new column.
This is just one of many ways to do this.
You can only do it if you have a lookup, be it an array or in another table that stores the keys and values.
You should be carefuly not to store the post data directly into your database without sanitizing it, otherwise you might become subject to sql injection.
Is there anyway to put the name of the option into the database instead of the value?
There is, but it involves doing it explicitly (converting "10" into "Excellent" before inserting the value) rather than just basically tossing $_POST into the database as-is. You can make this very simple if you are building the <option>s with an array in the first place by reading the the array again and swapping the values with the keys.
$values = array(
10 => 'Excellent',
5 => 'Good',
0 => 'Poor',
);
$post_value = $_POST['state'];
$db_value = $values[$post_value];
// further validation: make sure the array key exists or use a default value
// further usage: build your HTML <options> with this array
However:
If you're going to do that, you're much better off storing the values as numbers and converting them to words when you display them (assuming the numbers do have some meaning). This also allows you to localize by providing translations.
Response to comments:
I would recommend a rating system, like 1 through 5, and calculate your price modifications internally - not directly from the user input or from a hardcoded value (in the database). This allows you to tweak the price changes from within your app, rather than from database values that were created at an earlier time, like if you decide an "Excellent" condition warrants an increase of 11 rather than 10 - unless you specifically want the prices "locked in" permanently at the time the product was posted.
Whatever you do, make sure to validate the input - I can't think of any good reason to use direct user input to calculate prices - it should be done internally based on product ids, and any other conditions. HTML source can be modified on-the-fly to post values you didn't expect from the dropdown.
You can't get it via the HTML form. But you can still do a server side that would map the values to the appropriate condition.
You can use a switch statement or an if statement to map them.
if(value == 10){
$condition = 'Excellent';
} else {//....}

Categories