Showing posts with label developer mysql. Show all posts
Showing posts with label developer mysql. Show all posts

Tuesday, September 6, 2011

cakephp check database configuration exist and connection alive valid

Keyword
Check cakephp database configuration exist
Check cakephp database can be connect

In cakephp you need to configure the connection
The configuration file was in app/config/database.php

Inside the file, you can see 2 variable which is 'default' and 'test'

By default is 'default' but if you want to use 'test' in the controller for example, you need to call it like this
$this->Mmodel->useDbConfig = 'test';
 

Problem arise is, can we connect to 'test' without problem?

So, here is the code I made. Been googling it and quite hard to found the solution, thus I'm putting this in my blog. lol...

This code will check
- Does the configuration 'test' exist
- If the configuration exist, does the database connection valid

If these 2 condition is pass, you can only have SQL Syntax Error like selecting table that does not exist

So here is the code (its free)
//Checking is done by connecting with the  database
if (class_exists('DATABASE_CONFIG')){
    $dbConfigName1 = 'test'; //<-- PUT YOUR DATABASE CONFIG VARIABLE NAME HERE

    $dbConfig1 = new DATABASE_CONFIG();
    //pr( $dbConfig1);                    

    if( isset( $dbConfig1->$dbConfigName1)){                       

        //Now check wether the database configuration, its alive!
        //pr( $dbConfig1->$dbConfigName1);
        $dbTemp1 =& ConnectionManager::getDataSource($dbConfigName1);

        if( $dbTemp1->isConnected() == true){

            //Means database exist and you can use it
            echo "DATABASE CONFIG '$dbConfigName1' EXIST AND MANAGE TO CONNECT";
        }
        else{

            //Database configuration exist, but cannot connect to the database
            echo "DATABASE CONFIG '$dbConfigName1' EXIST BUT FAILED TO CONNECT";
        }
    }
    else{

        //The database configuration does not exist
        echo "HAS NO DATABASE CONFIGURATION WITH NAME '$dbConfigName1'";
    }
}
else{

    //The database.php file not even exist. How can this be? IMPOSIBIEBERBEL!
    echo "CANNOT FIND THE 'database.php' CONFIGURATION FILE";
}

Reference
http://bakery.cakephp.org/articles/T0aD/2009/07/08/handle-database-connection-errors
http://debuggable.com/posts/handling-database-connection-errors-in-cakephp:480f4dd5-9570-421a-a04d-43cdcbdd56cb

Thursday, August 11, 2011

mysql I need to remember script

SELECT colourid, COUNT(colourid) as noofoccurance FROM vtiger_appendixcolour WHERE colourid != 0 GROUP BY colourid ORDER BY noofoccurance DESC;
This is to find each colourid, how much frequency it has been used. Typically use this to find 'search by popularity;

Friday, May 6, 2011

phpmyadmin too many table in database cause pagination

Too many table will automatically create a page pagination

If you are using phpmyadmin version 3.3.9, and your table in the database is alot (about 600 table)
then the page number will appear (these called pagination in web term, I think)

These page number is quite annoying since I remember some important table name from the database and having a page number slow me down cause I search the table name by using "Ctrl + F" from Google Chrome
Thus, when I Ctrl+F and type the table name, it does not appear...

Note that phpmyadmin work best when using Google Chrome (because of its "Ctrl +F" function) compared to Firefox, Opera and Safari (I have test them all and these in only an opinion)

So, the reason behind all my problem lies in the default config @global integer $cfg['MaxTableList'] where it will do a pagination for database table (set default into display 250 table in a page)

The reason, change this and all problem solved!

So, regarding on which IDE did you use in programming, search globally (in whole project) for string name @global integer $cfg['MaxTableList']

If you are using windows with WampServer Version 2.1, the phpmyadmin program is located at C:\wamp5\apps\phpmyadmin3.3.9

If you are lazy or not have a capability to find the whole project, here is the location
C:\wamp5\apps\phpmyadmin3.3.9\libraries\config.default.php (on line 501)

thats all, hope its usefull

Monday, March 14, 2011

Install LAMP on Ubuntu

These is a double posting, the original was from here http://asipi.blogspot.com/2009/10/haih.html

I write it back here because the title and here will be the latest updated place
(Yes I do update these post again if got any changes)


1

Install apache & mysql & phpmyadmin : http://www.howtoforge.com/ubuntu_lamp_for_newbies

*Update 23 Jan 2010
My Software source was from Malaysia and it has problem!. So it set my source to "Main Server" (Software source download from Main Server)


2

Enable the www folder
This will make your be able to add new folder into the localhost
using terminal :

sudo chmod -R 777 '/var/www'

Please note that /var/www is your root for the website
/var/www/smellynomore means http://localhost/smellynomore


3

You will realize that u cant open the phpmyadmin on http://localhost/phpmyadmin
This is because when you see inside /var/www there is no "phpmyadmin" folder

Solve it by referring here http://ubuntuforums.org/showthread.php?t=1036836

Solve by doing this in terminal :

sudo ln -s '/usr/share/phpmyadmin' '/var/www'



4

Additional configuration for the mysql

When you first time install the mySQL, everything is working fine.
But then, after you reboot the PC, the mySQL server cant start.

The mySQL configuration file will be missing after boot
After some haih...checking, you will realize that file inside "/var/run/mysqld" is missing

I solve it by this link, http://ubuntuforums.org/showthread.php?t=386056
Try to chown to "mysql.mysql" if owned by root, and give it a 755
It is because of the folder write permission

How to chown and chmod, please note that I dont know what happen to security issue when I done this, just want to 'make it work!'

sudo chown -R asipo '/var/run/mysqld'
sudo chmod -R 777 '/var/run/mysqld'




5

Load the mod_rewrite module
I google here to solve it http://ubuntuforums.org/showthread.php?t=255556&page=2

Using terminal :

sudo a2enmod rewrite
sudo gedit /etc/apache2/sites-enabled/000-default


After that change AllowOverride None to AllowOverride All

Then, restart Apache

sudo /etc/init.d/apache2 force-reload



6

Additional, command to mySQL server (check, start, restart and stop)
http://abbysays.wordpress.com/2008/05/20/how-to-startstop-mysql-server-on-ubuntu-804/

Setting up the cakePHP 1.2.5
There will be 2 problem
1. Warning (512): /var/www/cakemake/app/tmp/cache/ is not writable [CORE/cake/libs/cache/file.php, line 262]
2. Your tmp directory is NOT writable.

Solve by : Once again chmod 777 is not secure, yeah!

sudo chown -R asipo '/var/www/smellynomore/app/tmp'
sudo chmod -R 777 '/var/www/smellynomore/app/tmp'




7

Install x-debug
http://ubuntuforums.org/showthread.php?t=525257

EDITED #2 (Feb 2011)
I dont know why lately my xdebug does not working. So I edit the php.ini file
I make the all to be "Deleopment mode" because its defaulted to "Production mode"
So I guess that is the reson, plus use this on ERROR Report
error_reporting = E_ALL & ~E_DEPRECATED & ~E_NOTICE


8

After that, it will read index.html
I dont know how to change it for the thing to refer into index.php

However, this is the index.php code (simple version of mine)

<p><b>Localhost</b></p>
<p>Select folder or file to navigate</p>

<?php

echo "<ul>";
if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            echo "<li><a href='$file'>$file<a></li>";
        }
    }
    closedir($handle);
}
echo "</ul>";
?>
If you have been wandering how I put this code into this blog. This is the place http://asipi.blogspot.com/2011/01/write-blog-post-using-tinymce.html

Thus when you open your http://localhost/index.php will get something like this


9

phpMyAdmin login might be annoying, solve it from here http://asipi.blogspot.com/2011/02/disable-phpmyadmin-login.html


10 Edit 28 Nov 2012
To install CURL. I follow this website http://buzznol.blogspot.com/2008/12/install-curl-extension-for-php-in.html

Basically, in terminal type : sudo apt-get install curl libcurl3 libcurl3-dev php5-curl
Then restart the LAMP server, then test it using var_dump(curl_version()); make sure to put -pre- html tag around it

Note that to restart the server. Using this command seems to be even better. Feel like it was relly restarting... sudo /etc/init.d/apache2 restart

Thats all
good luck, kupo!

Thursday, February 17, 2011

Disable phpmyadmin login

PhpMyAdmin is a webbased database management application and it is a very good tool for developer.

But there is one problem if you want to install it localhost which is annoying login after AFK for a while

I have google for these solution and the result wasnt good enough so I post this so I can refer it back

Manage to work it out by referring the manual http://www.phpmyadmin.net/documentation/#servers_user


Nows lets disable the annoying login

Advantage: no annoying
Disadvantage: Less secure, password stored in a file without encrypted

These was tested on Ubuntu machine version 10.10 so I'm not sure about windows
The version of phpmyadmin is 3.3.7deb3build0.10.10.1

1st open the configuration of the phpmyadmin file

sudo gedit /etc/phpmyadmin/config.inc.php



Search for string "/* Authentication type */" (its at line no 35)
Disable the "cookie" auth_type and put these code. It should look like these

/* Authentication type */
//$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = 'mypasswordissecret';


So you eventually change the auth_type into 'config' and you required to put the username and password for that

To test the annoying login is now disabled, restart your FireFox (reset the cache) and try to direct to the phpmyadmin (In my case I type "http://localhost/phpmyadmin/" in my FireFox URL)

It work when you are not asked for login. KUPO!

p/s: I know the file was /etc/phpmyadmin/config.ini.php is from file /var/www/phpmyadmin/config.inc.php

Edit 29 Nov 2012
For phpMyAdmin 3.4.11 the configuration file for windows was in libraries/config.default.php
here is my setting, for localhost development
$cfg['Servers'][$i]['auth_type'] = 'config'; //Default is cookie
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '';
$cfg['Servers'][$i]['nopassword'] = true; //Default is false
$cfg['Servers'][$i]['AllowNoPassword'] = true; //Default is false

Wednesday, January 5, 2011

CakePHP connect 2, many, multiple database

Tag
CakePHP connect with more than 1 database
CakePHP connect multiple database
CakePHP connect more database
CakePHP connect 2 database
CakePHP connect with 2 database. 1 is CakePHP structured and another 1 is not

The main source is from here
http://blog.4webby.com/posts/view/6/cakephp_models_using_multiple_db_connections

Repeat the same thing
class DATABASE_CONFIG {

var $default = array(
'driver' => 'mysql',
'persistent' => false,
'host' => 'your_host',
'login' => 'your_login_1',
'password' => 'your_password_1',
'database' => 'DB_1',
'prefix' => ''
);

var $general_syst = array(
'driver' => 'mysql',
'persistent' => false,
'host' => 'your_host',
'login' => 'your_login_2',
'password' => 'your_password_2',
'database' => 'DB_2',
'prefix' => ''
);
}
?>

class User extends AppModel {

var $name = 'User';
var $useDbConfig = 'general_syst';

//your code here
//....
}

class Post extends AppModel {

var $name = 'Post';
var $useDbConfig = 'default';

//your code here
//....
}

$this->Post->bla_bla_bla : data will be retrieved/inserted/updated from DB_1
$this->User->bla_bla_bla : data will be retrieved/inserted/updated from DB_2


Here is some additional
1. I can connect even without make it persistance.

pr($this->Student->useDbConfig);
$this->Student->useDbConfig = 'general_syst';
$ret = $this->Student->query("SELECT * FROM tbl_lecturer");


Note that tbl_lecturer is another non cakePHP database. It used MySQL database and query does take the data nicely

If you want to check the database connection. Refer here http://asipi.blogspot.com/2011/09/cakephp-check-database-configuration.html

Thursday, November 25, 2010

mysql find duplicate record

I take it from here. Put in my own blog cause I keep using them
http://www.petefreitag.com/item/169.cfm

SELECT email,
COUNT(email) AS NumOccurrences
FROM users
GROUP BY email
HAVING ( COUNT(email) > 1 )

SELECT email
FROM users
GROUP BY email
HAVING ( COUNT(email) = 1 )

31 May 2011
It turns out these code was pretty awesome when I want to make a dynamic drop down selection
I can make it display unique value and sorted by most use at the top

Tuesday, September 28, 2010

Software Architecting Success Factors and Pitfalls

My boss give to my email so sharing it with myself

Software Architecting Success Factors and Pitfalls

The top critical success factors for the architecting effort that we have identified are:

The architecting effort must:

* address a strategic business objective of your key sponsor
* have a good lead architect with well-defined role and style
* have a lead architect and architecture team who are able to "sell" (lead); conversely, the organization must be willing to "buy into" (follow)
* contribute immediate value to developers (utilizers of the architecture)

The architecture is more likely to be successful if:

* there are architecture advocates at all levels of the organization
* architecture is woven into the culture
* there is customer involvement/pressure/demand

Critical Success Factors

* Interpersonal and team communication and ownership
* Leadership
* Vision
* Teamwork
* Availability of talent/resources
* Must have strong management sponsorship
* Market/business understanding
* Good match between technology and business strategy
* Customer focus
* Clear specifications including dependencies
* Simple architecture
* Deployed in phases/incrementally
* Architecture is understandable by all
* Solve at least the current problem
* Validation of requirements during each step of the process
* Project management

The architect must have the following skills:

* good domain knowledge
* good communicator/listener
* good persuader
* good project management skills

The architect must

* have a clear and compelling vision
* champion the cause
* provide constructive feedback

Pitfalls

* Poor leadership
* Thinking at too low a level
* Poor communication inside/outside the architecture team
* Not enough "selling"
* Lack of resources/talent
* Poorly designed roles and responsibilities
* Bad design/idea
* Lack of extensibility
* Doesn't solve the project team's problems
* Lack of control/authority
* Requirements unclear, not well-defined, not signed off, changing
* Architecture team loses touch with the product team's problems
* Product team believes "we can solve it better ourselves"
* Development management not penalized for "stalling"
* Politics

Sunday, May 23, 2010

Playing with date

Since I easily forget about MySQL date function. I wrote this to myself.

I have a field name `created` with DATETIME format like 2010-05-24 11:24:05

Using the MySQL function
SELECT NOW() give you the latest time like 2010-05-24 11:24:05

SELECT CURDATE() give you the current date like 2010-05-24

So I available command is. Lets say the current time is 2010-05-24 11:24:05
SELECT YEAR( NOW()); will return 2010
SELECT MONTH( NOW()); will return 05
SELECT DAY( NOW()); will return 24
SELECT TIME( NOW()); will return 11:24:05
SELECT HOUR( NOW()); will return 11
SELECT MINUTE( NOW()); will return 24
SELECT SECOND( NOW()); will return 05

*Note
SELECT YEAR('2010-05-24 11:24:05'); will also return 2010


To select a record in the same month
SELECT * FROM table WHERE YEAR(`created`) = YEAR(CURDATE()) AND MONTH(`created`) = MONTH(CURDATE())

Another format is like this
SELECT name, created FROM customer
WHERE created BETWEEN '2010-01-04 00:00:00' AND '2010-01-06 00:00:00';

*Take note the field registerdate format is DATETIME()
*Take note that the date range in the between must be from low to high

These is a function to take the 'current amount from stock forecast'. Let say with these situation
15 March 2011, Gold price will be 2.0
20 March 2011, Gold price will be 2.1
30 March 2011, Gold price will be 2.2

Today is 25 March 2011. So the SQL will return "Gold price will be 2.1"
So these is the SQL
"SELECT `goldprice` FROM `vtiger_goldforecast` WHERE `datestart` <=CURDATE() ORDER BY `vtiger_goldforecast`.`datestart` DESC LIMIT 1";



Update 1.2 (25 Nov 2011) - Select a record within a date
Case: The table has start date and end date. You want to retrieve a record where today is still withing the start and end date

SELECT * FROM special eventWHERE NOW( ) BETWEEN startdate AND enddate


Thats for today, version 1.1
Going to update later

Thursday, May 13, 2010

CakePHP utf8 special character chinese character

i involve in some database with a chinese character.
It turns out my find('all') give me "????" for the chinese character

After some google, this is because database encoding. Its need to be utf-8
So this is the link thats help me http://nik.chankov.net/2007/10/01/cakephp-and-character-set-in-the-database/

Conclusion is, inside the database.php put the 'encoding'
class DATABASE_CONFIG {

var $default = array(
'driver' => 'mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'user',
'password' => 'password',
'database' => 'project_name',
'prefix' => '',
'encoding' => 'utf8'
);
}


What will happen actually is before any SQL query is executed.
It will execute this code first, I think.
"SET NAMES 'utf8'"


Just to remind something. If there is a case you table Collation/charset is not utf-8 means you will not be able to use Chinese character. So here is the tweak
ALTER TABLE 'tblcustomers' COLLATE utf8_general_ci;


And still, my website did not display the chinese character.
So I end it with
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=utf8"$gt;

and the problem is solve

Yeah!

Tuesday, May 11, 2010

MYSQL Export

I involve in some project where I need to do Export mysql table into .csv file

First of all, the table structure
CREATE TABLE IF NOT EXISTS `contacts` (
`id` int(20) unsigned NOT NULL auto_increment,
`name` varchar(200) NOT NULL,
`phonenumber` varchar(50) NOT NULL,
`group` varchar(50) NOT NULL,
`created` datetime default NULL,
`modified` datetime default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Contact detail' AUTO_INCREMENT=5 ;

INSERT INTO `contacts` (`id`, `name`, `phonenumber`, `group`, `created`, `modified`) VALUES
(1, 'Mr Number 1', '0126784669', 'Customer', '2010-05-12 09:50:57', '2010-05-12 09:50:57'),
(2, 'Mrs Testing', '0136785186', 'Customer', '2010-05-12 09:50:57', '2010-05-12 09:50:57'),
(3, 'Mr Bone', '0184531256', 'Staff', '2010-05-12 09:52:41', '2010-05-12 09:52:41'),
(4, 'Mr Gray', '0104578996', 'Staff', '2010-05-12 09:52:41', '2010-05-12 09:52:41');


Here is how to export the file into .csv
This code is in many blog and other tutorial
SELECT *
INTO OUTFILE "C:/Documents and Settings/asipo/My Documents/Downloads/contacts.csv"
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM contacts
WHERE `group` = 'Customer';


But most of the website I found, does not show how to create a .csv file with a extra column header description into it.
So this is how I do it
SELECT 'Id', 'Name', 'Phone Number', 'Group', 'Created', 'Modified'
FROM `contacts` LIMIT 1
UNION
SELECT *
INTO OUTFILE "C:/Documents and Settings/asipo/My Documents/Downloads/contacts.csv"
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY ''
LINES TERMINATED BY '\n'
FROM `contacts`

As a result, you going to see somthing like this


Thats all