Tuesday, 9 August 2011

MYSQL - mysql_real_escape_string error

Warning: mysql_real_escape_string() [function.mysql-real-escape- string]: Access denied for user 'SYSTEM'@'localhost' (using password: .......... 

If we have encountered the problem above, make sure we have made connection to the database before using the mysql_real_escape_string() function.

Thursday, 14 July 2011

CakePHP preg_match Error

Warning (2): preg_match() [function.preg-match]: Delimiter must not be alphanumeric or backslash...
If you have met a warning similar with above, you will have to check on the $pattern of the preg_match() function. According to php manual:

When using the PCRE functions, it is required that the pattern is enclosed by delimiters. A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character. 

So if your $pattern is a pure alphanumeric string,you will need to enclose the $pattern with delimiters such as / , or # or etc.

Monday, 27 June 2011

CakePHP Update ACL

Let's say we have created new controller(s). For authentication and security purposes, we will need to update the acl. If we are lazy to go through the bake cake console, we can try the following steps:

1. In initDb() function under controllers/acls_controller.php, defined the user groups properly. (the actions allowed/denied for each user group) Save the file.
2. Comment all functions/variables besides the Auth-related, in app/app_controller.php. (To make sure that initDb() will be executed).
3. In the web browser, type the url and launch it:
{address}/acls/initdb
4. Uncomment functions/variables in app/app_controller.php, if they were commented just now.

Wednesday, 22 June 2011

CakePHP - Parse Data From Controller To View

Let's say $a = '123', in index() in users_controller.
If we want to use the $a in users/index, we can use set() and compact():

$this->set(compact('a'));

*set() : Send data from controller to view.
**compact() : Creates an array containing variables and their values.
***Note that we need to remove the dollar($) sign when using compact().

Reference:
1. Stupid CakePHP Controller Tricks
2. Interacting with Views

Monday, 20 June 2011

CakePHP Trap: findAllBy() and find('all', ...)

I have a variable $productId. Comparing these two functions:


1. $pricelists = $this->PricesProduct->find('all',array('conditions'=>array('PricesProduct.id'=>$productId)));
$pricelists = $this->paginate('PricesProduct',$pricelists);


2. $pricelists = $this->PricesProduct->findAllByProductId($productId);
$pricelists = $this->paginate('PricesProduct',$pricelists);






If $productId = 1, the 2nd function will generate error but not for the 1st function.


Warning (512): SQL Error: 1054: Unknown column 'PricesProduct' in 'where clause' [CORE/cake/libs/model/datasources/dbo_source.php, line 684] 
Warning (2): Invalid argument supplied for foreach() [APP/views/...] 






Why?
I dont know the reason, but from the logs, two similar functions generated different sql codes:






For the 1st function:
1.  SELECT ... WHERE `PricesProduct`.`id` = 1,
which then generate normal sql code:
SELECT COUNT(*) AS ...  WHERE 1 = 1


For the 2nd function:
1. SELECT ... WHERE `PricesProduct`.`product_id` = 1,
which then generate the following problematic sql code:
SELECT COUNT(*) AS ... WHERE ((PricesProduct IN ('28', '1', '13' .....






I guess that findAllBy() is unable to generate a key for the find result, causing all data to be fed into the coming functions.


Therefore, it is advised to avoid using findAllBy() although it may have saved some programming time, yet it increase the risk of having to waste more time on debugging.
 
Sorry, it's my mistake that i myself is confused with two different functions that cause different result.
So, there is currently no trap in cakephp!

Monday, 13 June 2011

CakePHP Login Redirection

Let's said we want page to be redirected to Reservation index page after a User's login to the website, we can therefore create the login redirection in the beforeFilter() function in UsersController:
 
$this->Auth->loginRedirect = array('controller'=>'reservations', 'action'=>'index');
 
And, i really need to shout at CakePHP for having such a lousy documentation.

Thursday, 9 June 2011

CakePHP Drop Down List - Same value for 'keys' and 'values'

By default, when we use the form helper to generate a [select] drop down list, the [value] of each [option] is the [id] of the particular table. However, we sometimes need to have [value] which is the same as the content of the [option], therefore we will need to use array_combine() function.

We can do in such a way:
 $array1=array_combine($array1, $array1)
$array1 is an array of data. The first parameter will go to be the [key] of the new array and the second parameter will go to be the [value] of the new array, thus making both the [key] and the [value] of the new array having the same value.

Let's said :
$array1(
[1] => a
[3] => b
[4] => c
)

After using the array_combine() function, the $array1 becomes:
$array1(
[a] => a
[b] => b
[c] => c
)

Reference:
1. FormHelper - Setting Option Value in Select Dropdown
2. php.net - array-combine

Monday, 23 May 2011

Disabling CakePHP Auto Escape In Helpers

As we know, CakePHP will automatically escape special characters to sanitize the data.
Sometimes we do not want to escape the special characters, for example "Textarea" inputs, or some inline javascript (eg: onclick= "return function ('xxxx')" when we are using form/html helpers.
For these reasons, we can declared
'escape'=>false

in the $options (or $attribute ??) array.
As a result, the special characters in html code will be preserved.

Example:
echo $html->tableCells    (array    (array    ($form->checkbox('Checkbox1', array    ('escape'=>false,'onlick'=>'return checkbox(\'CheckboxCheckbox1\')')) ..... 


Reference:
Look for the first reply of the article.

Thursday, 19 May 2011

CakePHP - Matching Multiple Checkbox Inputs With Join/Cross Tables Without Magic

Given the situation: A `trainee` wants to select available time for courses. We have Table `days` and Table `sessions`, having a join table `days_sessions`. Each `days` may have 3 `sessions`, and  can select multiple `days` in the form. In the end, we end up with another join table like `trainees_days_sessions`

1. We have predefined data in `days_sessions`, e.g. Monday morning - 'MonM', Tuesday night - 'TueN', etc.
2. In the form we have checkboxes for each `days_sessions`. We may code it as

Input type='checkbox' id='data[DaySession][DaySession][]' name='data[DaySession][DaySession][]' value='*'/

Note that the `id` must be coded in such a way of data[model_name][model_name][] (as defined in your model), while the value (* sign) must be the `id` column in `days_sessions` table.

Thursday, 12 May 2011

Bake Cake MySQL error

If you have come across to warnings like
Warning: mysql_connect(): [2002] No connection could be made because the target machine actively in ...cake\libs\model\datasources\dbo\dbo_mysql.php on line...
PHP Warning: mysql_connect(): No connection could be made because the target machine actively refused it. in ...cake\libs\model\datasources\dbo\dbo_mysql.php on line ... 
And etc. Can try the following solution below:

1. Open php.ini
2. Look for the mysql.default_port, set it to the number accordingly, e.g.
mysql.default_port = 3306 

Fatal Error While Baking Cakes

Fatal error: Call to undefined function mysql_connect() in C:\...\cake\libs\model\datasources\dbo\dbo_mysql.php on line 600'
If you are using easyphp and have met this fatal error when baking cakes, can try this:
1. Copy php.ini from [easyphp]\apache to [easyphp]\php.

Reference:
Look for reply from andrej

Bake Cake with PHP in windows

In my case, i am using Windows 7.

1. Open cmd
2. CD to php directory
e.g. c:\program files\easyphp\php
3. Bake the cake using php.exe.
e.g. c:\program files\easyphp\php\php.exe "c:\[your localhost+project name]\cake\console\cake.php" bake
4. Start baking the cake!

Reference:
http://kodegeek.wordpress.com/2009/06/13/how-to-bake-on-windows-xampp-environment/

Tuesday, 10 May 2011

First Attempt With CakePHP

Currently learning from the IBM tutorial:
Cook up Web sites fast with CakePHP, Part 1: Getting started

I am using easyphp, and is go to set up the new cake as a production installation.

Several important steps:
1. In httpd.conf, set document root to:
DocumentRoot "${path}/www/cakephp/app/webroot" 


2. Also in httpd.conf, also set document root directory to
Directory "${path}/www/cakephp/app/webroot" 
...
 AllowOverride All
...


3. Setting up the database configuration:
Copy and rename the "app/config/database.php.default" into "app/config/database.php" and edit accordingly.


4. Create a user model:
 Create the file as "app/model/user.php" (or whatever name, as long as know how to handle)


5. Create a register view:
Create the file as "app/views/users/register.ctp


6. Create a controller and register action:
Create the file as "app/controller/users_controller.php". 



7. Bake it:
Go to the url: "http://localhost/users/register". 

Monday, 9 May 2011

CakePHP, EasyPHP and mod_rewrite

For a standard EasyPHP package, mod_rewrite is off in httpd.conf.
As using CakePHP requires the mod_rewrite, we will need to modify the httpd.conf of EasyPHP by just, uncomment it.

#LoadModule rewrite_module modules/mod_rewrite.so -> remove the hash

Tuesday, 3 May 2011

Switching Back To Opera Again

Since switching over to Chrome 15 months ago, now finally come back to Opera.

Opera 10 series, for me is quite a failure which contributes to the switch over, particularly in web compatibilities and extremely slow javascript execution speed as compared to chrome. (Or maybe i should say it is the result of following the protocols and procedures 100%?)

But now, Opera 11 is just as nice as Chrome, so it's time for me to come back to Opera again.

A major weakness for both web browsers:

Chrome 10: Sometimes will still crash when visiting some websites that contain flash applications.

Opera 11: Speed is still lacking a bit compared to chrome, but is very much faster than opera 10.

And don't ask/suggest me to use IE or Firefox unless they are proven...

Thursday, 21 April 2011

Using Apache As Server In A Local Area Network (LAN)

Let's said, you have set up server for LAN usage only. If you have ever come across to a page stating "Could not connect to remote server" or alike, can try out this solution.

1. Open the apache configuration file, httpd.conf.
2. Go to the section that configure the ip address.
3. Make sure it listen to the server's ip (not 127.0.0.1)
eg. Server's ip is 192.168.x.x using port 80, the make sure you have the following line :

Listen 192.168.x.x:80

Monday, 18 April 2011

Time Wasted On Nested Javascript Functions With onSubmit()

I want to create nested Javascript functions for my onSubmit() validation. However, it seems that my skill is still not there yet, (or there is javascript rendering problem in Opera?) where the form is still submitted even though the value returned for the onSubmit() is false.

So, the solution is:
Use back the old school method -- Structured programming without calling of nested functions!

And several hours has been wasted...

Wednesday, 13 April 2011

Internet Explorer 7 Failed To Render Simple Javascript and HTML DOM

Speechless, where i can use the same portion of code successfully in Opera, Chrome, Firefox and Safari...

Tuesday, 12 April 2011

CSS in PHP file

To enable css effects in a php file, just remember to declare !DOCTYPE (for HTML5) and HTML tag inside the php file.

HTML5 iframes line up horizontally

Feel troublesome when want to have several iframes lining-up horizontally? Because at least one of the iframes will move to the next row?

Solution: Make sure that the sum of iframes' "width" is less than 100%. (only applicable if you are using percentage for the width)

To Convert Microsoft Access Table Into MySQL Table - Part 2

There are some common practices to be done when doing this type of conversion:

1. Before converting Access file into CSV file, make sure
a) Data does not contain any backslash (\) and semicolon (;) -- programming common sense.
b) Be careful of the usage of any special characters, because utf8_bin will not recognize it.
c) In Access, when changing column of "Currency", it's better to change into "Text" but not "Number" because the decimal of the data will be removed when changing into "Number" whereas the decimal of data will still be kept if it is changed into "Text".

2. If using phpMyAdmin and MySQL, make sure
a) The format of date/datetime/timestamp and the number/currency/float/decimal in the Access file is compatible with the field formats in the MySQL table -- otherwise you will get something like 0000-00-00 00:00:00 for your datetime, or $123.00 in your price/amount field.
b) My suggestion is to set the date/time into text/varchar format for the conversion, and later change them into date/time format in MySQL using php, and so with the number/currency field.

3. Try to play with it, and you will know what i am talking about.

Monday, 11 April 2011

To Convert Microsoft Access Table Into MySQL Table

Currently using: Microsoft Access 2007, phpMyAdmin.

1. In Access, export into csv file.
a) export the table into text format, however in the file name, make sure the file extension is csv.
b) do not specify any export options.
c) choose 'delimited' format, my preference: delimiter - Semicolon, text qualifier - " -- to match with the options in phpMyAdmin later.
d) finish it.

2. In phpMyAdmin, import the csv file.
a) make sure that the database and tables are using collation of "utf8_unicode_ci", benefit: it will avoid the conversion of special characters when importing the csv file.
b) create a table where the field structure types are to be the same as in the Access table.
c) in the table, select 'import' and choose the csv file.
d) 'character set of the file' is 'utf8', 'Format of imported file' is 'CSV'.
d) finish it.

3. There it goes!