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

Aug 19, 2015

CakePHP 2.* how to use custom complex sql Query with model

Let's suppose that we have MySQL database with table categories:

CREATE TABLE `categories` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `category` varchar(64) DEFAULT NULL,
  `description` varchar(64) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB;


Then, in CakePHP framework, you want to call a simple query as you did it with mysql_query in PHP with no framework.

For that you have the class Model::query()

First, you build the model. You don't want to use predefined Models for a table (like the model Categories for DB table Categories). Because you want to use perhaps this query for extracting data from two tables which are related.

So,  first you have to create the model. For this you have to create the file APP/Model/Categs.php



class Categ extends AppModel {

    public $useTable = false; // it is mandatory to have this line. Whithout this line, 
                              //                                    the Controller will search for table Categ; it doesn't matter that you have a sql query  

    public function getDataFromMyTable(){
        $d = $this->query("SELECT * FROM  categories");
        return $d;
    }

}


Second, you have to create the Controller. The file will be: APP/Controller/CategsController.php


class CostsController extends AppController {
    
    
    public function index(){
        $this->loadModel('Categ');
    
        $rezQuery = $this->Categ->getDataFromMyTable();
        $this->set('cs', $rezQuery);
    }
}
?>


And now we have to create the view. We create folder APP/View/Categs (if this folder doesn't exists). And then we create the file index.ctp into this folder. The name of the ctp file should be the  same as name of the function from Controller. In index.ctp we write:


Mar 31, 2015

MySQL Conference at Oslo

A couple of weeks ago I went to a MySQL Conference which has been kept in Lysaker, Oslo at ORACLE Office.

17 March 2015, Lysaker, Oslo

It was a database conference at Oracle building about MySQL and MySQL News and the rest.

They develop more InnoDB for a better transactional operations.

Replication for a better scalability.

Swedish Police uses MySQL; also, Facebook, Booking.com, Linkedin, CISCO and others.


They, I mean these two guys, brought infos about MEM (MySQL Enterprise Monitor). I have to admit that I didn't know about that.

And, also, they said something about MySQL Query Analiser.

MySQL has a developers team at Trondheim.


MEM (MySQL Enterprise Monitor)

MEM (MySQL Enterprise Monitor) works on Apache. It is a Java Application. To monitorize a
MySQL Server you need to put an agent on your Database Server.



HADOOP

I have to see what they did about this. (80% big data platform).


MAX 2 TB for MySQL

SQL and NoSQL access to data.


SSD optimization




DUMP and RESTORE

mysql> SET innodb_buffer_pool_dump_at_shutdown=ON;


Transportable TABLES

FLUSH date for EXPORT;

Optimizer
EXPLAIN (this is used at the beginning and is not so precise)
….
OPTIMISER ( this is used at the end of a query and it has a better presentation as a result)
EXPLAIN [FORMAT=____] FOR CONNECTION ;
SERVER-SIDE STATEMENT TIMEOUT;
SELECT M;

MySQL Fabric

This is for using more databases, using mirrors. This is helping us not to do manual work when one of the servers is down. :(
There is a farm of MySQL Servers and they work like a team.

I'll be back with documentation. Here I've put only a short sketch of mine made into Conference.

Oct 31, 2012

New forum

Starting today, the coders has a new forum for their comunnication. Here we are:
coderstalk.co.cc

It is structurated by software domains: PHP, ASP, .NET, C#, Databases and HTML&CSS.
We are 4 people which will respond for every question.

The website is based on the SMF Simple Machines Forum.

Oct 22, 2012

New project


www.pasainternational.ro
This is my last project which is almost done: www.pasainternational.ro

For the first page and offers pages I have implemented a cahe system based on the json files.

The Cache is available for 2 hours.

Sep 18, 2012

Mysql Restore

This handy command line snippets allow us to import and export databases or tables with mysql built in function. Mysqldump command can be configured to export databases, or just a table.


//Export Database
mysqldump -uUsername -p Database > db_backup.sql
 
//Export Multiple databases
mysqldump -uUsername -p --databases db_name1 [db_name2 ...] > db_backup.sql
 
//Export All databases
mysqldump -uUsername -p --all-databases > db_backup.sql
 
//Export a table
mysqldump -uUsername -p Database Tablename > table_backup.sql
 
//Export multiple tables
mysqldump -uUsername -p Database Table1 [Table2 ...]  > tables_backup.sql



Restore database or tables from mysqldump file
mysql -u username --p database_name < dump.sql




Feb 28, 2012

New project

Today, we lance a new project. It is BETA version. But the website is Up. It's about http://www.dentaldirectorylinks.com. It is a link directory with/for dentists and dental network in the world.

It's all withh html, css javascript, jQuery, Mysql and PHP.

Dec 20, 2011

Creating XML from MySQL as easy as PI


ANALYSIS
Unfortunately, importing XML into MySQL is more like chocolate cheesecake, but there are solutions available. Just follow this guide and you'll be on your way to integrating Web services with your database in no time. Starting from scratch
With the growing popularity of XML, developers have found an easy method to present data sets in a standardised way. What else does that sound like? A database! It's only natural that it should be simple to convert your information without a lot of fuss -- and you can. Some proprietary database manufacturers, such as Microsoft and IBM, have taken steps to integrate XML into their systems. This comes as no surprise since these two companies are both heavily involved in the XML standardisation project. Not wanting to be left behind, the creators of MySQL database incorporated a means for generating an XML data file. It's supported in version 3.23.48 and up. You can use the command line or facilitate the process with the programming language of your choice. To get started, you can download MySQL database  for free from MySQL.com. The current release is sufficient to support this feature, and you don't need to compile it with any special parameters. Fruit filling
Once you're installed, created, and populated your database, execute the following command to generate an XML file:
mysqldump --xml databasename [tables]
If you'd like to save this to a file, simply use the standard *NIX method of outputting to a file:
mysqldump --xml databasename > filename.xml
This produces a well formed XML document. Because XML is datacentric, if you dump your entire database and it contains no information, your file will result in a series of empty tags based on the table names. Your output should look something like this:

Now you're free to use this data file with any application you desire. This method is useful in a number of ways. Not only will it create a standardised representation of your data, but it can also take a snapshot of your database (or portion of your database) for display. Rather than making repeated calls to the database server, just generate an XML document when your database changes and reference that from Web pages or whatever you're using. This can localize calls for data, reduce the overhead of frequent calls to a database, and easily present a subset of your information for improved performance, security, or localization. Ice cream on the side
It's really easy to get XML from MySQL, but how about the other direction? That's a little trickier. MySQL itself doesn't support this function, and with good reason. The database currently has no way to validate the XML file. This could result in a number of scenarios, ranging from a partial load to ignoring malformed tags and statements to simply forcing the entire load to fail. MySQL supports only cascading back-outs in current development versions. While it's not pretty from a native standpoint, you do have some options. One solution is Perl's DBIx::XML_RDB module. You can use this method to both import and export XML, though understandably the import is heavily dependent upon a correctly structured XML file. To get the data, the module essentially runs a query and formats the results in an XML file. Conversely, you can use the module to read an XML file, create a SQL query, and execute it. There is a simpler option as well. The DBIx::XML_RDB module ships with two utility scripts to facilitate the process: xml2sql.pl and sql2xml.pl. I found agreat tutorial  on using this Perl module at O'Reilly's XML.com Web site. It will walk you through the process. Another, more generalized effort comes from Ron Bourret's XML-DBMS project . This is an ongoing effort to support XML imports and exports with relational databases using Perl and Java. There's also some very interesting work that supports mapping one database to another using XML as facilitating middleware. This is a community-oriented open source project being managed on SourceForge . Other languages, particularly Web scripting languages, haven't ignored the need to import XML into SQL databases either. There are similar efforts for Python, such as the xml2sql and dtd2sql modules, outlined in detail in this article from IBM , and a couple of projects in the works for PHP, such as the "XML MySQL class" project. Scrumptious
With these utilities, importing and exporting XML into and from MySQL is easy! Since MySQL is popular and free, it's been the test bed for integrating many scripting languages in XML, and as a result there are a number of tutorials and scripts specific for this database. With the power of a relational database and the ability to easily create XML files, MySQL can be an integral part of your Web services solution.

Nov 23, 2011

Learn How to Install Joomla on Your Website in Less Than 5 Minutes


You can learn how to install Joomla on your website in a number of ways. However, the simplest and by far, the quickest is through Fantastico. This usually takes about 1-2 minutes once you know how. In this article, we are going to cover just that.

So, here is the step by step process for installing Joomla on your own website.

1. Log in to your hosting account's Control Panel. This should usually be http://www.mydomainname.com/controlpanel, where 'mydomainnane' is replaced your own website that is hosted on that hosting account.

2. Look for the smiley icon that says "Fantastico" and click on it. This is where you will be installing the Joomla package from. Note that Sometimes, it may say "Fantastico De Luxe." Don't worry it is the same thing. Much like saying "my room" and "my bedroom" ;)

3. Look for "Joomla" under the "Content Management" category of scripts in Fantastico and click on it. Also, note that the title 'Joomla' may sometimes have some numerical suffixes showing which version it is. For example, the title may read "Joomla 1.5" for version 1.5 of the CMS. Just click on the most recent version and go to the next step.

4. Look for the hyperlinked blue "New Installation" link and make sure you have at least as much as the minimum disk space required for you to install Joomla on your website. This is usually about 25 MB of disk space.

This is not usually
a problem, with most people's disk space running into the tens of gigabytes. But it is still good to make sure you have enough to hold a new Joomla installation.

5. Choose where on your website you want to install Joomla. Will it be on your main domain, an existing sub-domain or a new not-yet-existing sub-domain or directory? Indicate it in this part of the installation process.

6. Fill out other required fields that are required to smoothly install Joomla on the site. This includes creating an Admin username and password. Don't choose 'Admin' and 'password' as your username and password. Many people do this and have been hacked. Also, fill out the site name or main keyword, email address and other details here.

Then click the "Install Joomla" button.

7. On the next page, make sure that all the needed information is correct. Also, note down your Admin username, password and backend page (the one that ends with /administrator).

Finally, hit that "Finish Installation" of a button.

Voila! You have just learned how to install Joomla on your website. This should usually take only 1 or 2 minutes at most. After all, all you are doing is just hitting buttons, except for when choosing a username, etc.

If it still sounds a little like "nerd talk" (with all due respect to all the nerds out there ;) ), you can watch the video version of this article where you see the Joomla installation done live on the screen and see if you can learn how to install Joomla after that.

Jun 7, 2011

Mysql - Modify an existing MySQL column

The best laid plans of mice and DBAs oft go awry, so it is sometimes necessary to change the characteristics of a column after it exists and contains data. Beware whenever you make changes to your database — always make a backup first.


After a week of using the contacts table created inCreate a basic MySQL table, we may find that 40 characters for the column name doesn’t cut it. To increase the size of the name column to 80 characters:
ALTER TABLE contacts CHANGE name name VARCHAR(80);
The first part of this statement (ALTER TABLE contacts CHANGE name) identifies that we want to change the column name in the table contacts. The second part of this statement (name VARCHAR(80)) redefines the column name. We could further define this column as NOT NULL, for example, with
ALTER TABLE contacts CHANGE name name VARCHAR(80) NOT NULL;

Apr 8, 2011

Mysql Temporary tables

he temporary tables could be very useful in some cases to keep temporary data. The most important thing that should be knows for temporary tables is that they will be deleted when the current client session terminates.
Temporary tables where added in MySQL version 3.23. If you use an older version of MySQL than 3.23 you can't use temporary tables, but you can use heap tables.
As stated earlier temporary tables will only last as long as the session is alive. If you run the code in a PHP script, the temporary table will be destroyed automatically when the script finishes executing. If you are connected to the MySQl database server through the MySQL client program, then the temporary table will exist until you close the client or manually destroy the table.

Example

Here is an example showing you usage of temporary table. Same code can be used in PHP scripts using mysql_query() function.
mysql> CREATE TEMPORARY TABLE SalesSummary (
    -> product_name VARCHAR(50) NOT NULL
    -> , total_sales DECIMAL(12,2) NOT NULL DEFAULT 0.00
    -> , avg_unit_price DECIMAL(7,2) NOT NULL DEFAULT 0.00
    -> , total_units_sold INT UNSIGNED NOT NULL DEFAULT 0
);
Query OK, 0 rows affected (0.00 sec)

mysql> INSERT INTO SalesSummary
    -> (product_name, total_sales, avg_unit_price, total_units_sold)
    -> VALUES
    -> ('cucumber', 100.25, 90, 2);

mysql> SELECT * FROM SalesSummary;
+--------------+-------------+----------------+------------------+
| product_name | total_sales | avg_unit_price | total_units_sold |
+--------------+-------------+----------------+------------------+
| cucumber     |      100.25 |          90.00 |                2 |
+--------------+-------------+----------------+------------------+
1 row in set (0.00 sec)
When you issue a SHOW TABLES command then your temporary table would not be listed out in the list. Now if you will log out of the MySQL session and then you will issue a SELECT command then you will find no data available in the database. Even your temporary table would also not exist.

Dropping Temporary Tables:

By default all the temporary tables are deleted by MySQL when your database connection gets terminated. Still you want to delete them in between then you do so by issuing DROP TABLE command.
Following is the example on dropping a temproary table.
mysql> CREATE TEMPORARY TABLE SalesSummary (
    -> product_name VARCHAR(50) NOT NULL
    -> , total_sales DECIMAL(12,2) NOT NULL DEFAULT 0.00
    -> , avg_unit_price DECIMAL(7,2) NOT NULL DEFAULT 0.00
    -> , total_units_sold INT UNSIGNED NOT NULL DEFAULT 0
);
Query OK, 0 rows affected (0.00 sec)

mysql> INSERT INTO SalesSummary
    -> (product_name, total_sales, avg_unit_price, total_units_sold)
    -> VALUES
    -> ('cucumber', 100.25, 90, 2);

mysql> SELECT * FROM SalesSummary;
+--------------+-------------+----------------+------------------+
| product_name | total_sales | avg_unit_price | total_units_sold |
+--------------+-------------+----------------+------------------+
| cucumber     |      100.25 |          90.00 |                2 |
+--------------+-------------+----------------+------------------+
1 row in set (0.00 sec)
mysql> DROP TABLE SalesSummary;
mysql>  SELECT * FROM SalesSummary;
ERROR 1146: Table 'TUTORIALS.SalesSummary' doesn't exist

MYSQL index

A database index is a data structure that improves the speed of operations in a table. Indexes can be created using one or more columns, providing the basis for both rapid random lookups and efficient ordering of access to records.
While creating index it should be considered that what are the columns which will be used to make SQL queries and create one or more indexes on those columns.
Practically, Indexes are also type of tables which keeps primary key or index field and a pointer to each record in to the actual table.
The users cannot see the indexes, they are just used to speed up queries and will be used by Database Search Engine to locate records very fast.
INSERT and UPDATE statements takes more time on tables having indexes where as SELECT statements become fast on those tables. The reason is that while doing insert or update, database need to inert or update index values as well.

Simple and Unique Index:

You can create a unique index on a table. A unique index means that two rows cannot have the same index value. Here is the syntax to create an Index on a table
CREATE UNIQUE INDEX index_name
ON table_name ( column1, column2,...);
You can use one or more columns to create an index. For example we can create an index on tutorials_tbl using tutorial_author
CREATE UNIQUE INDEX AUTHOR_INDEX
ON tutorials_tbl (tutorial_author)
You can creates a simple index on a table. Just omit UNIQUE keyword from the query to create simple index. Simple index allows duplicate values in a table.
If you want to index the values in a column in descending order, you can add the reserved word DESC after the column name:
mysql> CREATE UNIQUE INDEX AUTHOR_INDEX
ON tutorials_tbl (tutorial_author DESC)

ALTER command to add and drop INDEX:

There are four types of statements for adding indexes to a table:
  • ALTER TABLE tbl_name ADD PRIMARY KEY (column_list) : This statement adds a PRIMARY KEY, which means that indexed values must be unique and cannot be NULL.
  • ALTER TABLE tbl_name ADD UNIQUE index_name (column_list):This statement creates an index for which values must be unique (with the exception of NULL values, which may appear multiple times).
  • ALTER TABLE tbl_name ADD INDEX index_name (column_list):This adds an ordinary index in which any value may appear more than once.
  • ALTER TABLE tbl_name ADD FULLTEXT index_name (column_list):This creates a special FULLTEXT index that is used for text-searching purposes.
Here is the example to add index in an existing table.
mysql> ALTER TABLE testalter_tbl ADD INDEX (c);
You can drop any INDEX by using DROP clause along with ALTER command. Try out following example to drop above created index.
mysql> ALTER TABLE testalter_tbl DROP INDEX (c);
You can drop any INDEX by using DROP clause along with ALTER command. Try out following example to drop above created inde x.

ALTER Command to add and drop PRIMARY KEY:

You can add primary key as well in the same way. But make sure Primary Key works on columns which are NOT NULL.
Here is the example to add primary key in an existing table. This will make a column NOT NULL first and then add it as a primary key.
mysql> ALTER TABLE testalter_tbl MODIFY i INT NOT NULL;
mysql> ALTER TABLE testalter_tbl ADD PRIMARY KEY (i);
You can use ALTER command to drop a primary key as follows:
mysql> ALTER TABLE testalter_tbl DROP PRIMARY KEY;
To drop an index that is not a PRIMARY KEY, you must specify the index name.

Displaying INDEX Information:

You can use SHOW INDEX command to list out all the indexes associated with a table. Vertical-format output (specified by \G) often is useful with this statement, to avoid long line wraparound:
Try out following example:
mysql> SHOW INDEX FROM table_name\G
........