I'm a noob in cakephp. Working on an opensource project. The issue is:
When I'm inserting a value for a certain table ( "is_adjusted" (tinyint)), the my php code executes successfully. But the table is only taking 0 or 1 as it's value. Sample code :
$reward = $ta_customer_reward->newEntity();
$string_reward = var_export($reward, true);
$reward->customer_email = $some_preset_xyz;
$reward->reward_amount = $some_preset_xyz;;
$reward->particulars = $some_preset_xyz;
.. .. ..
// This is_adjusted is the culprit.
$reward->is_adjusted = 2;
$reward = $ta_customer_reward->save($reward);
Now whenever I save (insert) this in db, this is stored as 1. I'm stuck for three days. Things I've checked:
No default value in db for is_adjusted.
No other function is overwriting that field.
*** 1.The reward object looked quite unusual to me. There is a property name dirty. I'm still studying this. But for now it seems to me as some cakephp db object structure.
This is cakephp v 3. xyz***
This is by CakePHP's design. CakePHP always see tinyint(1) as boolean hence it will always convert your value to true/false hence the 1/0.
To overcome this issue, use tinyint(2) instead for your column type. Remember to clear your model cache!
CakePHP data type documentation:http://book.cakephp.org/3.0/en/orm/database-basics.html#data-types
Blog post about this:http://blog.room34.com/archives/2649
Similar Q&A:CakePHP and tinyint as boolean
Related
I have table (~150 columns with ~150k records) and project on Symfony 3 with Doctrine. In project is clasic filter to show results.
If you submit form i collect data in object $selectedInputOptions and build query looks like:
$query = $repository
->createQueryBuilder('t')
->select('t.idkatcountry', 't.idkatlocality', 't, MIN(t.price) AS priceFrom'......);
if(count($selectedInputOptions->getCountry()) > 0)
$query->andWhere('t.idkatcountry IN (:idkatcountry )')->setParameter('idkatcountry ', $selectedInputOptions->getCountry());
if(count($selectedInputOptions->getLocality()) > 0)
$query->andWhere('t.idkatlocality IN (:idkatlocality )')->setParameter('idkatlocality ', $selectedInputOptions->getLocality());
price column have decimal(15,2) datatype
Before i have in $repository->select('t.price') and everything was OK but after change this to 't, MIN(t.price) AS priceFrom' query execution time was increased +40% and in few cases (any input in form be blank = checks all records) +900%.
So my questions:
How i can cut execution time? (Is there some idexes for this?, Will help change datetype range let's say to decimal(6,2)?)
And bonus question :) Table has ~150columns but query for filtering using ~10-15 columns can i set some type of index for quicker selects?
EDIT:
changed column price to ineger - did not help
added index to column pricte - did not help
SOLUTION!
It was little mistake in select parameter using MIN().
Insted of:
't, MIN(t.price) AS priceFrom'
I used:
'MIN(t.price) AS priceFrom')'
Because t takes ALL columns (~150 in my case) and I didn't notice this... So now is everything OK and time is normal.
Here you can do one thing, stop loading unwanted data in entity, by using unset in jsonSerialize() method.
I have a problem, that I do not know how to solve. This is my code:
$sql_current_animal = "SELECT orders.animal, farm.capacity FROM orders LEFT JOIN farm ON orders.animal=farm.serial WHERE orders.id ='$id';";
foreach ($pdo->query($sql_current_animal) as $current_animal_row) {
$current_animal = $current_animal_row['animal'];
$capacity_animal_arr[$current_animal] = $current_animal_row['capacity'];
}
The type of capacitywas in my database int(11). When it was like that my code worked very well. But now I need to change the type of capacity to varchar(225). I still have the same value of capacity in my database (for example: 2), but my code is not working anymore. What exactly happens is, everything is displayed on my page to this line and after this my page is blank.
The problem must be in this line: $capacity_animal_arr[$current_animal] = $current_animal_row['capacity']; because when I delete this line, everything is displayed on the page again.
It might be that the rest of your script expects capacity to be of type Integer. Try converting the value in PHP to int. Here's how:
$capacity_animal_arr[$current_animal] = intval($current_animal_row['capacity']);
Please confirm if it works for you.
Firstly echo the value of $current_animal_row['capacity'] and $current_animal_row['animal'] before line $capacity_animal_arr[$current_animal] = $current_animal_row['capacity'].If you will get correct value of capacity and animal then problem is not from db.
I need to update two columns in a table in mysql. I have written following code in ZF2 model
$sql = new Sql($dbAdapter);
$update = $sql->update();
$update->table($table_name)
->set(array('checksum' => '', 'mailed_status' => 0))
->where('id = ' . $record_id);
$statement = $sql->prepareStatementForSqlObject($update);
$statement->execute();
Here in the above code, checksum is varchar column and mailed_status is bit column. The above query only updates checksum field but the mailed_status remains same (previously 1)
When I was updating mailed_status as 1, it works. I mean it updates 0 to 1 but the vice versa is not working.
I have printed the query and found that it makes quote around digit like this: '0' and '1'.
But I am wondering here. '1' is working but '0' is not, why?
What is the proper solution for this? Temporarily I changed the bit data type to varchar(1) in mysql database's table.
Thanks
Thats because 0 is treated like a Null value when updating your database. Changing column type to varchar(1) it's simpler than override sql update method!
I'm just learning PHP and I've searched for a while on this, but I'm afraid I may not know exactly how to ask it, so an explanation will probably work best. Basically I have a group by/count query returning 3 records.
Status Total
0 2
1 3
2 2
On my page I would like to display:
Status Total
Dev 2
Active 3
Arch 2
So I basically just want to assign the values 0, 1 and 2 to a text value. I've tried creating an array, then assigning the return number field equal to the array.
$_status = array(0 => 'Development', 1 => 'Production', 2 => 'Archive');
while($rowStat = mysql_fetch_assoc($resDev))
{
echo "<tr><td>$_status[$rowStat['status']]</td><td>{$rowStat['devprojects']}</td></tr>";
};
Any help is much appreciated.
Thanks.
as you can see here http://php.net/mysql_fetch_assoc the field names are case sensitive
from what I see in your table sample the field is called "Status"
and you are using "status"
you can try changing
$rowStat['status']
to
$rowStat['Status']
Edit:
the initial version of the answer only focused on what's the problem (and suggested pdo)
I only want to add that I agree to two other optinions found here:
the one added via comment to this answer by giorgio: you should only use lowercase names for your database fields; also you should consider using the table name as a prefix (product_id instead or id, user_password instead of password) for two main reasons: to avoid colisions when you fetch results using a join and to avoit collisions with mysql reserved words (as id, password and status are)
the other one, suggested by Crashspeeder by a comment to the question: you definitely should develop with error reporting on and disable it on live servers
I don't really like using the 0, 1, 2 to represent a named value (unless you have a relational) table in your DB... but using your setup, why not just use:
while($rowStat = mysql_fetch_assoc($resDev)){
switch($rowStat['Status']){
case 0:
echo "<tr><td>Development</td><td>{$rowStat['devprojects']}</td></tr>";
break;
case 1:
echo "<tr><td>Production</td><td>{$rowStat['devprojects']}</td></tr>";
break;
case 2:
echo "<tr><td>Archive</td><td>{$rowStat['devprojects']}</td></tr>";
break;
}
};
EDIT
Some people really are looking for copy-paste answers so here's an updated answer because Sgt. Crashspeeder of the Massively Anal Society got her knickers in a twist.
Create a lookup array to reference against the status Ids:
$statusArray[0] = 'Development;
$statusArray[1] = 'Production;
$statusArray[2] = 'Archive;
Then when you're running your mysql_fetch_assoc() loop, you can reference the statusArray lookup like so:
while($rowStat = mysql_fetch_assoc($resDev)){
echo "<tr><td>{$statusArray[$rowStat['Status']]}</td><td>{$rowStat['devprojects']}</td></tr>";
}
I have a MYSQL table with an ENUM field named "offset" and some other columns. The field is defined as:
ENUM(0,1), can be NULL, predefined value NULL
Now I have two server. A production server and a development server and the same PHP script used to create and to update the database.
First step: the application create the record witout passing the "offset" in the CREATE query.
Second step: the application ask to the user some data (not the "offset" value), read the row inserted in step one and make an array, update some field (not the "offset" field), create a query in an automated fashion and save the row again with the updated values.
The automated query builder simple read all the field passed in an array and create the UPDATE string.
In both systems I obtain this array:
$values = array(... 'offset' => null);
and convert it in this same query passing the values in the mysql_real_escape_string:
UPDATE MyTable SET values..., `offset` = '' WHERE id = '10';
Now there is the problem. When i launch the query in the production system, the row is saved, in the development system I got an error and the db says that the offset data is wrong without saving the row.
From phpmyadmin when I create the row with the first step, it shows NULL in the offset field. After saving the field in the system which give no errors, it show me an empty string.
Both system are using MySQL 5 but the production uses 5.0.51 on Linux and development use 5.0.37 on Windows.
The questions:
Why one system give me an error an the other one save the field ? Is a configuration difference ?
Why when I save the field which is an enum "0" or "1" it saves "" and not NULL ?
Why one system give me an error an the other one save the field ? Is a configuration difference ?
Probably. See below.
Why when I save the field which is an enum "0" or "1" it saves "" and not NULL ?
According to the MySQL ENUM documentation:
The value may also be the empty string ('') or NULL under certain circumstances:
If you insert an invalid value into an ENUM (that is, a string not present in the list of permitted values), the empty string is inserted instead as a special error value. This string can be distinguished from a "normal" empty string by the fact that this string has the numeric value 0. ...
If strict SQL mode is enabled, attempts to insert invalid ENUM values result in an error.
(Emphasis added.)
strager's answer seems like a good explanation on why your code behaves differently on the 2 environments.
The problem lies elsewhere though. If you want to set a value to NULL in the query you shound use exactly NULL, but you are using mysql_real_escape_string() which result is always a string:
$ php -r 'var_dump(mysql_real_escape_string(null));'
string(0) ""
You should handle this differently. E.g:
$value = null
$escaped_value = is_null($value) ? "NULL" : mysql_real_escape_string($value);
var_dump($escaped_value);
// NULL
Some DB layers, like PDO, handle this just fine for you.
If you want it to be NULL, why don't you do this in the first place:
UPDATE MyTable SET values..., `offset` = NULL WHERE id = 10;