I want to use ENUM in my class but TINYINT in my database. I followed this article: https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/cookbook/mysql-enums.html
In my Mysql table:
CREATE TABLE `side` (
`coated` tinyint(1) DEFAULT NULL COMMENT '0 = Uncoated; 1 = Coated',
);
In my class:
/**
* #ORM\Column(type="string", columnDefinition="ENUM('coated', 'uncoated')")
*/
private $coated = null;
Running the values in PHP I get the real value from database:
0 or 1
I'm wondering if this solution works using Mysql. Hope having a solution, if this won't work the only solution I find is:
public function getCoated() {
if ($this->coated === 0){
return "uncoated";
} elseif ($this->coated === 1) {
return "coated";
} else {
return null;
}
}
Instead of using "TINYINT" I suggest to use "BIT" data type, so that database will only allow storing the values as "0" or "1" to be in safe side.
Your existing:
CREATE TABLE `side` (
`coated` tinyint(1) DEFAULT NULL COMMENT '0 = Uncoated; 1 = Coated'
);
Change it to:
CREATE TABLE `side` (
`coated` BIT DEFAULT NULL COMMENT '0 = Uncoated; 1 = Coated'
);
In "TINYINT" it can also accept the values other than 0/1 that might be create a bug in your application if someone updated your table data to like 2,3,4.
Related
I want to develop website with option to select language
at the time I do not know about how to structure my database tables i.e
either I should add separate fields for each language e.g
tbl_posts
id, title_en,title_fr,description_en,description_fr,....
or should I get help of google translate at run time
or there is something else easy to do this
secondly I will need to have URLs like
www.domain.com/en/posts/ & www.domain.com/fr/posts/
third what other things should I keep in mind to develop multilingual website.
looking for standardized, more optimized, easy manageable and fully dynamic solution.
Cakephp
Step 1: In your lib/Cake/basic.php add function
if (!function_exists('__dbt')) {
function __dbt($text, $args = null) {
if($text==null){
return null;
}else{
$languageUse = Configure::read('Config.language');
if($languageUse!='en-us' && $languageUse!='eng'){
$modelName = ucfirst($languageUse)."Translation";
$model = ClassRegistry::init($modelName);
$data = $model->find('first',array('fields'=>array('translation'),'conditions'=>array("text"=>"$text")));
if(!empty($data[$modelName]) && $data[$modelName]['translation']!=''){
return $data[$modelName]['translation'];//die('1');
}else{
// Please copy & paste below code from your basic.php __() function
App::uses('I18n', 'I18n');
$translated = I18n::translate($text);
$arguments = func_get_args();
return I18n::insertArgs($translated, array_slice($arguments, 1));
}
}else{
// Please copy & paste below code from your basic.php __() function
App::uses('I18n', 'I18n');
$translated = I18n::translate($text);
$arguments = func_get_args();
return I18n::insertArgs($translated, array_slice($arguments, 1));
}
}
}
}
Step 2: create table on basis of language you want to use
Note: table name should be prefix locale + _tranlations
example: hin_translations, tha_translations etc.
CREATE TABLE IF NOT EXISTS `hin_translations` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`text` text NOT NULL,
`translation` text NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
In above table add english string in your text column and its translation in translation column.
Step 3: where ever you want to change language string either from database or locale po file just use
__dbt("Write your string here");
:) enjoy your multilingual site
Just a simple function in native php
protected function some_function(){
session_start();
if(!isset($_SESSION['a']))
{
$_SESSION['a'] = 'some value';
return true;
} else {
return $_SESSION['a'];
}
}
on the 1st run, it will return bool(true) and then "some value" as expected.
Applying the same to laravel session,
protected function some_function(){
$a = Session::get('abc');
if(is_null($a)){
Session::put('abc', 'some value');
//return Session::get('abc');
return true;
} else {
return $a;
}
}
By logic, on the 1st run, $a will be null. and then puts "some value" in abc key and returns bool(true) as expected.
However on consequent access, the Session::get('abc') returns null every time. so every attempt returns bool(true).
I assumed may be session wasn't writing properly so i checked with getting the key value right after setting it.
by commenting out the line in the above code, it returns whatever value i put in Session::put('abc'). So there is no error in writing the data.
Problem here is trying to retrieve the value always returns null though i have set after the 1st request.
Am i missing something here?
EDIT
Using database as the driver, The sessions does not get save in database. No error is outputted. Database implementation has been correct with sessions table schema as described in docs.
Try this snippet. Untested, but pretty sure it works.
if(Session::has('abc'))
{
return Session::get('abc');
} else {
Session::put('abc', 'some value');
return true;
}
After going through many forum to solve same issue, I solved it by setting my session driver to database.
'driver' => 'database',
and created table in database
CREATE TABLE `sessions` (
`id` varchar(40) NOT NULL,
`last_activity` int(10) NOT NULL,
`data` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
I am a beginner in cakePHP , i want to save some data into my database , but i always get : the Message : Sorry, Error while saving data.
Here is my code : ( Controller : UsersController.php : ( and i have added the Model 'UserState to the array $uses )
if($onbreak == 'true'){
$userStatus = 1;
//$response['userStatus'] = 1;
} else {
$userStatus = 0;
//$response['userStatus'] = 0;
}
//add the new user_status to the $newUserState
$newUserState['UserState']['user_id'] = $userID;// $userID = 1
$newUserState['UserState']['user_status'] = $userStatus;
//adding values for fields which should not be NULL
$newUserState['UserState']['user_phone_nb'] = '4343';
//
saving data
if($this->UserState->save($newUserState)){
$response['success'] = 'true';
$response['message'] = '';
}else{
$response['success'] = 'false';
$response['message'] = 'Sorry, Error while saving data.';
}
Thanks in advance
EDIT :
Structure of the table userstates :
id : BIGINT primary key AUTO INCREMENT,
user_id : INT NOT NULL,
user_status : SMALLINT NOT NULL,
user_phone_nb = VARCHAR(15) NULL
the Model Userstate :
class Userstate extends AppModel {
var $useTable = 'userstates';
public $name = 'UserState';
}
EDIT 2 :
when i debugg the variable $newUserState i got this ( which seems that is OK ) :
Array
(
[UserState] => Array
(
[user_id] => 18
[user_status] => 0
[user_phone_nb] => 4343
)
)
I'm not sure what you are doing here,
could you post your table structure and the insert-query cake is generating? You find that on the bottom if you use the standard cake-layout and have debugging mode on.
I suspect (but am not sure without further data) that there is another field in the table wich needs a value (cannot be null).
I am assuming the field in the DB is 'userStatus' and there is only one value to save. But this should work and you should be able to expand on it to save other values.
Hope this helps.
Saving a new Record
if($onbreak == 'true'){
$userStatus = 1;
} else {
$userStatus = 0;
}
//add the new user_status to the $newUserState
$newUserState['UserState']['user_id'] = $userID;// $userID = 1
$newUserState['UserState']['user_status'] = $userStatus;
//adding values for fields which should not be NULL
$newUserState['UserState']['user_phone_nb'] = ' ';
// Must include id as it is a primary Key and thus required for saving.
$newUserState['UserState']['id'] = $userstate_id;
//saving data
if($this->UserState->save($newUserState)){
$response['success'] = 'true';
$response['message'] = '';
}else{
$response['success'] = 'false';
$response['message'] = 'Sorry, Error while saving data.';
}
Ok try this.
Rename your Model to user_state.php
Then add the following to it, based on Cake 1.2 cookbook
http://book.cakephp.org/view/436/useTable
<?php
class Userstate extends AppModel {
var $useTable = 'userstates';
public $name = 'UserState';
}
Also in the config/core.php make sure the line with debug reads as follows.
Configure::write('debug', 2);
Try this and let me know your results.
Does this work for you:
$this->UserState->set('UserStatus', 'New title for the article');
$this->UserState->save();
I hope it helps
i found the solution,
in my Model , i have the variable $validate with some parameters which have the required variable setted to true. so i've three Solutions :
First :
just commenting the variable and dont use it ^^
Second:
just initialize the required variables with a default value.
Third :
i found that in the doc , we can tell cakePHP to save our data without perform validation :
save(array
$donnees = null, boolean $valider = true, array $listeDesChamps = array())
so all what i did is saving data and passing the second parameter with a false value like this : $this->UserState->save($newUserState, false); , ( personally i've used this Third Solution ^^ )
Thanks you all for your help :)
Regards,
Some tips at the end:
For cases like these it's nice to have multiple validation sets made possbile by this: http://bakery.cakephp.org/articles/dardosordi/2008/07/29/multivalidatablebehavior-using-many-validation-rulesets-per-model
Next time post complete code. The validation thing would be first guessed if you hadn't post just a 4 line represenation of your model which everyone thought was final.
You should reinclude the sql dump in your layout. It will not show up in live mode due of DEBUG => 0 and will help you enormous in situation like these.
I think the class name of the UserState model should be "UserState" and like already mentioned the file name "user_state.php". That would save a line of code :P
Greetings
func0der
I've module and I've update to alter database table, shortly I need to do something like
ALTER TABLE `TABLE` ADD `FIELD` INT UNSIGNED NOT NULL AFTER `SOME_FIELD`
so is there any built in function in Drupal to make this changes I considered db_add_field function didn't work?
Sultan
Using db_add_field()
db_add_field('TABLE', 'FIELD', "VARCHAR( 255 ) NOT NULL DEFAULT '0' AFTER FIELD_2");
The above does not work, for one it leaves out the first argument (the reference to $ret) and the fourth argument will not allow a raw sql query, only a structured array.
What I had to do was this (change hook_update_N to modulename_update_XXXX as per the drupal api documentation of course):
function hook_update_N(&$sandbox) {
// We use update_sql here, instead of db_add_field because we cannot specify
// AFTER in the db_add_field.
$ret = array();
$ret[] = update_sql("ALTER TABLE {table} ADD `FIELD` INT UNSIGNED NOT NULL AFTER `SOME_FIELD`");
return $ret;
}
Hope this helps someone else.
I'm adding "promo code" functionality to an online shopping cart written by someone else. This is a pretty micky mouse architecture question, but I would like to hear a couple of opinions. All three of my ideas would work, but which do you think is best for maintainability?
So, here's the basic table structure for the promo codes:
CREATE TABLE `promocodes` (
`promocode_id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`promocode` VARCHAR( 255 ) NOT NULL ,
`description` VARCHAR( 255 ) NULL ,
`discount_percentage` INT NULL ,
`discount_dollars` DECIMAL( 6, 2 ) NULL ,
`expiration_date` DATE NULL ,
`uses_remaining` INT NULL ,
`is_active` BOOL NOT NULL DEFAULT '1'
)
What's the smartest (without getting overcomplicated):
Check existence with SQL, everything else seperately in code
// LIBRARY
function promoCodeExists($promoCodeString){
// make sql call
return $promoCodeDetailsHash; // or false if no record
}
function isPromoCodeUsable($promoCodeDetailsHash){
// check expiry date and number of uses left and active / inactive
}
function usePromoCode($promoCodeId){
// do order association
// decrement uses left
}
// USAGE
$promoCodeDetailsHash = promoCodeExists($promoCode);
if (is_array($promoCodeDetailsHash) AND isPromoCodeUsable($promoCodeDetailsHash)){
usePromoCode($promoCodeDetailsHash['id'])
} else {
// invalid promo code
}
Or, have a validation function but have it called only by the get function:
// LIBRARY
function validatePromoCode($promoCodeDetailsHash){
// check expiry date and number of uses left and active / inactive
}
function isPromoCodeUsable($promoCodeString){
// make sql call
return validatePromoCode($promoCodeDetailsHash); // or false if no record
}
// USAGE
$promoCodeDetailsHash = promoCodeExists($promoCode);
if (is_array(isPromoCodeUsable($promoCodeDetailsHash))){
usePromoCode($promoCodeDetailsHash['id'])
} else {
// invalid promo code
}
Check everything in SQL with invalid the same as nonexistance:
// LIBRARY
function getDetailsForUsablePromoCode($promoCode){
// use SQL WHERE clauses to only return existence for currently valid promo codes
// or false if no result
}
// USAGE
$promoCodeDetailsHash = getDetailsForUsablePromoCode($promoCode)
if (is_array($promoCodeDetailsHash)){
usePromoCode($promoCodeDetailsHash['id'])
} else {
// error state
}
Feel free to point out any other approaches or wackness here.
In my application, I create it as 2 table. First table just like you, but only hold the usage_limit as integer. In second table, I will hold the usage, one usage per row.
In the promocode_usage table, I will have promocode_id as foreign key, and other required column such as usage datetime, user id, etc. To check if the promo is still available, I will simply count the row in promocode_usage table that have promocode_id I want to check. If the result less than usage_limit value, the promo can be used.