Symfony: conditional validator

Here we will see how to implement a conditional validator for Symfony’s forms.

As you may know the form framework inside Symfony gives us the ability to use validators for each form field, therefore we can validate the required fields, the data format, etc.

When we need to validate certain logic for a field which could not be accomplish it with the normal Symfony validators, we have to use a post validator. A post validator is executed after all normal Symfony validators and it receives an array with all entered values through the form.

As a practical case, we might want to validate that an entered password in a login form is equal to the entered username. Obviously, this is a easy but practical example.

The login form could be as follow:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?php
class loginForm extends sfForm
{
    public function configure()
    {
        $this->setWidgets(array(
            'username'  => new sfWidgetFormInput(),
            'password'  => new sfWidgetFormInputPassword(),
        ));
 
        $this->setValidators(array(
            'username' => new sfValidatorString(array('required' => true)),
            'password' => new sfValidatorString(array('required' => true)),
        ));
 
        $this->widgetSchema->setNameFormat('login[%s]');
 
        // add a post validator
        $this->validatorSchema->setPostValidator(
            new sfValidatorCallback(array('callback' => array($this, 'checkPassword')))
        );
    }
 
    public function checkPassword($validator, $values)
    {
        // before validating the password, check that the username is not empty
        if (!empty($values['username']) && $values['password'] != $values['username']) {
            // password is not correct, throw an error
            throw new sfValidatorError($validator, 'Invalid password');
        }
 
        // password is correct, return the clean values
        return $values;
    }
}

In this way, the validator callback will throw a “global” error when the entered password is not equal to the entered username. If we want to get a specific field error we should modify the checkPassword() method:

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
public function checkPassword($validator, $values)
{
    if (!empty($values['username']) && $values['password'] != $values['username']) {

        $error = new sfValidatorError($validator, 'Invalid password');
 
        // throw an error bound to the password field
        throw new sfValidatorErrorSchema($validator, array('password' => $error));
    }
 
    return $values;
}

That is! I hope it’s helpful.

Unix basic commands

This is a recompilation of helpful commands for Unix systems.

 

List directory content

To list the content of a specific directory we can use the ‘ls’ command. The syntax is ls [options] [directory] being the ‘-l’ a really helpful option, which shows the directory content with details:

1
2
3
user@unix:~$ ls -l
drwxr-xr-x 2 user user 4096 2010-03-10 00:03:45 Desktop
drwxr-xr-x 2 user user 4096 2010-01-19 22:33:05 Documents

 

The pipe “|” command

This command allows us to pipe the outputs and inputs of other processes. The concatenation of pipe commands is very helpful and powerful, and it is really used on Unix systems. An example is:

1
user@unix:~$ cat fichero1 fichero2 | grep palabra | sort | uniq

 

The tee command

tee is a command using standard streams which reads standard input and writes it to both standard output and one or more files, effectively duplicating its input. It is primarily used in conjunction with pipe.

1
user@unix:~$ sh deploy.sh | tee deploy.txt

 

Symlinks

To create symbolic links we can use the ‘ln’ command. For instance:

1
user@unix:~$ ln -s /path/to/link [new_alias]

With the above command we create a file named ‘new_alias’ which points out to the ‘/path/to/link’.

 

Show the last lines of a file

The command ‘tail’ shows the last lines of a file. For instance:

1
user@unix:~$ tail -f -n 10 file.txt

Shows the last 10 lines of the file.txt file.

 

Show the command documentation

A really helpful command is the ‘man [command]’ command which shows the documentation of the given command , for instance:

1
user@unix:~$ man tail

It will show the documentation for the tail command.

 

Flush DNS cache

If we need to flush our DNS cache we could run:

1
user@unix:~$ sudo /etc/init.d/dns-clean restart

 

Count files and/or folders

Sometimes we need to kwno how many files and/or folders we have in a specific path, to do that we could run:

1
user@unix:~$ ls -lR | grep ^d | wc -l

 

Check disk usage

If we want to check the usage of our hard disk we should run:

1
user@unix:~$ du -h -a /dir | grep "[0-9]G\b"

 

Count files in folder

Note that it doesn’t count hidden files and assumes that file names don’t contain newline characters.

1
user@unix:~$ ls | wc -l

 

 

How to use Subversion from command line

Here we will see how to use Subversion from CLI (Command Line Interface).

As you may know, there are SVN clients like Tortoise for Windows or RabbitVCS for Linux, but in this post we will only cover CLI (my favourite way ;-)).

Initialize a project work copy in my local machine: svn checkout

To get a work copy of source files in their last version we need to execute a process to copy all the files in our file system, this is accomplished with the checkout command:

1
user@unix:$ svn checkout https://svn.hasheado.com/svn/hasheado/trunk hasheado-repo --username=hasheado

The above command will copy all files in our file system and all files are ready to be edited. Now, you can edit existing files, create new files and/or directories or remove files locally. Keep on mind that everything change we make, it only affects our local copy until we commit the changes to the svn repository.

Add files/directories: svn add

We can add a new file to the repository after create it and editing it in our local copy, or well, add a directory with or without content using the svn add command. This command will add the files/directories from your local copy and they will be added to the repo in the next commit. Also, we can change our minds and revert whatever we do not want using the svn revert command.

1
2
user@unix:$ svn add css/style.css
user@unix:$ svn revert

View file information: svn blame and svn cat

We can see the information about the author and revision number for specific files, using the svn blame FILENAME command; each line in the file is displayed at the beginning with the author (svn username) and revision number of the last change for the line.

If we want to see the differences in an specific file before to commit our changes, we can run the svn cat command.

Unlock a work copy

Sometimes we can see a “working copy locked” error. So, to unlock it, we can run:

1
user@unix:$ svn cleanup

Copy a file/directory: svn copy

Sometimes we have the need to just copy a file, to do this we can use the svn copy command as we can see below:

1
user@unix:$ svn copy SRC DST

Delete a file/directory: svn delete

If we want to delete a file or directory we can use:

1
user@unix:$ svn delete FILENAME

And to persist the deletion we need to commit.

Export a directory without .svn files: svn export

With this command we can extract a work copy with no version (without .svn files), to export a directory without .svn files we can run:

1
user@unix:$ svn export [-r REV] [PATH]

This will export a non-version work copy from the specified repository, we can specify the version as well, if no version is specified the head revision (HEAD) is exported. If the PATH is omitted, the last url is used to export.

1
user@unix:$ svn export PATH1 PATH2

SVN help

We can use the SVN help to see how to use every command:

1
user@unix:$ svn help [SUBCOMMAND...]

Send changes to repository

After we have made the changes locally in our files and/or directories, we should commit those changes to the repository.

Commit the changes: svn commit

To commit the changes to the repo:

1
user@unix:$ svn commit -m "Type your comment here" [files]

If we do not include any comment in the commit, we should add it in the default text editor which is triggered before SVN can complete the commit. All commits are logged into the SVN log.

Show commit logs: svn log

If we want to see the history of files or directories in our local copy or in the repo to track the revisions we can run:

1
user@unix:$ svn log [PATH]

The result is information about the files/directories, starting with the most current revision and showing information like the commit’s messages and authors.

Merge changes: svn merge

We can run the svn merge command to tell to Subversion that it should merge the last versions of the repo files into our local work copy.

Working with the repository

Create a new directory: svn mkdir

To create a new directory in your local work copy:

1
user@unix:$ svn mkdir PATH

Or, to create a new directory in the repo:

1
user@unix:$ svn mkdir URL

The end part of PATH or URL determines the new directory’s name. The new directory in the repo is created with an inmediate commit which requires a commit’s message.

Move a file/directory: svn move

We can move a file/directory using the svn move SRC DST command, with SRC being the source and DST the destiny. This command is equal to make a svn copy followed by a svn delete.

Resolve conflicts: svn resolved

In some situations we can get a conflict while we update our work copy. If this is the case, we need to resolve the conflict and then mark it as resolved. To do that we need to run:

1
user@unix:$ svn resolved PATH

SVN status

A good practice is to review our changes before to commit them, for that we can run svn status to print the file/directory status in our local copy.

Update our local copy: svn update

Another good practice is to update the local work copy every time we start working in the project, running:

1
user@unix:$ svn update [PATH...]

The updated items with their status are displayed as:
* A = A file was added to the local copy.
* U = A file was updated in our local copy.
* D = A file was deleted in our local copy.
* R = A file was replaced in our local copy.
* G = A file was successfully merged.
* C = A file has conflicts that we need to resolve.

Branching and Tagging

The project trunk is normally the main development thread, while the branches are used to different variants of that main development thread. For instance, when we want to build a new feature we can create a new branch to work on it. A tag is a way to group stable versions of the project. Although, the branches and tags are created using the svn copy command, their concepts are totally different. To create a branch/tag we have to run:

1
user@unix:$ svn copy SRC DST -m "Type your message here"

How to send emails with Symfony 1.3 / 1.4

In this post we will see how to send emails with Swift Mailer through Symfony.

As we mentioned in an earlier post, Symfony comes with an already integrated mailer library. And, send an email is as simple as we can see below:

1
2
3
4
<?php
public function executeSendEmail() {
    $this->getMailer()->composeAndSend('from@example.com', 'to@example.com', 'Subject', 'Body');
}

Or, you can chose for compose the message and then send it with the Send() method:

1
2
3
4
5
<?php
public function executeSendEmail() {
    $this->getMailer()->compose('from@example.com', 'to@example.com', 'Subject', 'Body');
    $this->getMailer()->send();
}

Furthermore, if we need to add a little more of complexity like attach a file, it is as simple as we can see below:

1
2
3
4
5
6
<?php
public function executeSendEmail() {
    $this->getMailer()->compose('from@example.com', 'to@example.com', 'Subject', 'Body')
        ->attach(Swift_Attachment::fromPath('/path/to/a/file.zip'));
    $this->getMailer()->send();
}

As we can observe in the previously used methods Symfony handles mailing issues with a Mailer object, which is got it with the getMailer() method, already ready to use in the controller due to that the mailer object already is part of the Symfonyโ€™s core.

Configuration

By default, the send() method tries to use the local SMTP server to send the message, but, of course, as a lot of Symfony stuff this is totally configurable.

As we mentioned previously the Mailer object is part of the Symfony’s core. These objects are automatically built, configured and handled them by the framework. All of the core objects are configurable by the factories.yml file.

The default configuration looks like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
mailer:
  class: sfMailer
  param:
    logging: %SF_LOGGING_ENABLED%
    charset: %SF_CHARSET%
    delivery_strategy: realtime
    transport:
      class: Swift_SmtpTransport
      param:
        host: localhost
        port: 25
        encryption: ~
        username: ~
        password: ~

When a new application is built, the factories.yml file overwrites the default configuration with some sensitive environments variables:

1
2
3
4
5
6
7
8
9
test:
  mailer:
    param:
      delivery_strategy: none

dev:
  mailer:
    param:
      delivery_strategy: none

The delivery_strategy option tells to the framework how to deliver the messages. By default, Symfony comes with 4 different strategies:

  • realtime: The messages are delivered in real time.
  • single_address: The messages are delivered to just one single email address.
  • spool: The messages are stored in a queue.
  • none: The messages are just ignored.

It does not matter what the strategy is, the messages are always logged them in the log and they are available in the “mailer” tab in the web debug toolbar.

Mail Transport

The emails are always send them through a transport. You can configure the transport that you want just editing the factories.yml file. The default configuration is:

1
2
3
4
5
6
7
8
transport:
  class: Swift_SmtpTransport
  param:
    host:       localhost
    port:       25
    encryption: ~
    username:   ~
    password:   ~

We can chose between 3 different classes:

  • Swift_SmtpTransport: Uses the SMTP server to send messages.
  • Swift_SendmailTransport: Uses sendmail to send messages.
  • Swift_MailTransport: Uses the PHP native function mail() to send the messages.

In the “Transport Types” section into the official Swift Mailer documentation we can find everything we need about the transport classes and their different parameters.

Source: Symfony’s site

Doctrine vs Propel

UPDATE: Here is a great comparison for these ORM’s for the 2.x versions. Thanks to @Pati for sharing the link.

A quick comparison for the most 2 well known and best ORM‘s for PHP.

Here we will try to make a quick comparison about the most known ORM for PHP. To help developers to take the right decision when we need to decide what is the best ORM which could best adapt to our projects.

These 2 more used ORM are as the post title mentioned Doctrine and Propel.

Features

Both ORMs have many similar basic features, they support all the usual operations for CRUD (Create, Retrieve, Update and Delete), from create a new record to update existing ones. Also, both can generate the PHP classes for you, Propel based on XML while Doctrine based on YAML, And another cool feature they have is that both support different database engines (like Mysql, Oracle, MSSQL, etc).

Both support data validation and model relationships. Additionally, they support simple inheritance, although in Doctrine is called concrete inheritance. Doctrine supports 2 types of inheritance: Simple, where all the classes have the same columns, and the Aggregation inheritance, where we store an additional value in the table which allows us the automatic instantiate of the right model type when we make a query.

Well, we saw they almost share the same features so far, but the following are features only Doctrine has.

Behaviors: Doctrine supports many “behaviors” for its models, for instance, a Timestampable model will automatically create two columns: created_at and updated_at, where we can store the creation and update dates.

Searching: Doctrine has a fulltext search engine.

Plus, Doctrine supports data fixtures and migrations, caching, events, pagination, commands line interface and so on, and we can say in advanced features Doctrine has an advantage compared with Propel.

Usability

Documentation

One of the most important thing is documentation of course. Without a good documentation is hard to use any library. Until the last year (2009) the Propel documentation was one of the major problem for them, and it’s true they are improving it there still are work to do. In the other hand, the Doctrine documentation is great and the community is continuously improving it. So, about documentation concern, Doctrine is clearly the winner.

Libraries Use

The first task we have to do with both ORMs is to build the model classes. Doctrine allows us to just write a simple YAML file, or just PHP code if you prefer it. The Propel proposal is to write a XML to define our model classes, and in my personal opinion I prefer to deal with YAML instead of XML, so point for Doctrine :-).

Database operations

The basic operations with CRUD are very similar in both ORMs, however, there is a big different when we need to do more advanced queries.

Propel uses a Criteria/Peer proposal:

1
2
3
4
5
6
<?php
$c = new Criteria();
$c->add(UserPeer::ID, 10);

//SELECT all "User" models which have 10 as their ID and join all foreign tables.
$users = UserPeer::doSelectJoinFoobar($c);

Doctrine proposal is to use Doctrine_Query and a simple customized SQL named DQL (Doctrine Query Languaje):

1
2
3
4
5
6
<?php
$items = Doctrine_Query::create()
    ->from('User u')
    ->leftJoin('u.Foobar')
    ->where('u.id = ?', 10)
    ->execute();

To set values in our model classes these ORMs utilizes different methods: Doctrine uses magic methods, while Propel generates setters and getters. This feature gives to Propel the advantage of autocompletion in most IDEs.

As conclusion I can say that both ORM are great, but I prefer Doctrine. And, of course, you can put the ‘My opinion’ label to this post.

And in this link you can find a comparison that Symfony made between these 2 ORMs.

HTTP Errors

A list of most known HTTP errors.

These errors belong to the HTTP/1.1 standard and they are classified in five different types.
The five different defined types are:

1xx. Informational. The request is received and it continues with the process. The errors in this range indicate provisional responses. The Web Servers should not send 1xx errors to the client, except under experimental conditions.

2xx. Success. These errors indicate that the request was received, understand, accepted and successfully processed.

3xx. Redirection. In this range the client should do aditional actions to complete the request. The required action should be carry by the User Agent with no user interaction only if the method is GET or HEAD. The user agent should not automatically redirect more than five times, if not is considered an infinite loop.

4xx. Client Errors. These errors are triggered when the error is in the client.

5xx. Server Errors. The server fails when it looks like the request is not valid or the server is unable to do the request.

1xx Informational.

100 Continue. The server has received the request headers and the client should proceed to send the request body.

101 Switching Protocols. The client asks to the server to change protocols and the server knows if it could do it.

102 Processing. As a request can contain many sub-headers, this could take so much time to complete the request. This error indicates that the server has received and is processing the request, but it does not response that it’s not available yet. This avoids the client to assume that the request was lost.

2xx Success.

200 OK. This is the standard response for a successful HTTP request. The response will depend in the used method (GET, PUT, POST, etc).

201 Created. The request has been completed and the response is that a new resource was created.

202 Accepted. The request has been accepted to be processed, but it has not been completed yet.

203 Non-Authoritative Information. The server has processed the request successfully, but it’s returning information what could be from another source.

204 No Content. The server processed the request successfully, but there is not content to return.

205 Reset Content. It’s identical to 204 error but with the difference of the response requires the client to reset the resource.

206 Partial Content. The server is returning the resource partially. This error is used in tools like wget.

207 Multi-Status. The body of the response is a XML message and it could contain separated status depending in how much sub-requests were done.

3xx Redirect.

300 Multiple Choices. It indicates multiple options for the resource the user is requesting. For instance, it could be used to present different options to video formats.

301 Moved Permanently. The current request and all future requests to the requested resource should be redirected to the given url.

302 Found. This is the most popular redirect error, the HTTP/1.0 requires the client to make a temporal redirect, but the most popular browsers implement 302 error as 303 error. Therefore, HTTP/1.1 added the 303 and 307 errors to distinguish between these two behaviors, most web applications still use the 302 errors like a 303 error.

303 See Other. This error was added in HTTP/1.1. The response for the rrequest could be find in other URI using the GET method.

304 Not Modified. It indicates that the resource was not modified since the last request.

305 Use Proxy. This error was added in HTTP/1.1. Some HTTP clients (like Mozilla and Internet Explorer) do not handle this error properly, mainly due to security reasons.

307 Temporary Redirect. This error was also added in HTTP/1.1. In this case, the request should be repeat it with another URI, but the future requests could use the original URI. In contrast with 303 error, the HTTP method should not be changed.

4xx Client Errors.

400 Bad Request. The request contains wrong syntaxis or it could not be completed.

401 Unauthorized. This error is similar to 403, but it is specifically used when the user can authenticate but the authentication has been failed or has not been entered the authentication credentials yet.

402 Payment Required. This error is reserved for future uses and it’s thinking to be used for applications those make payments.

403 Forbidden. The request was legal, but the server rejects to response it.

404 Not Found. The requested resource is not found, but it could be in the future.

405 Method Not Allowed. The resource was requested via a not allowed HTTP method. For instance, try to process a form with a GET method instead of a POST.

406 Not Acceptable. The requested resource only can generate content no acceptable by the request headers.

407 Proxy Authentication Required.

408 Request Timeout. The server triggered a timeout.

409 Conflict. It indicates tha the request could not be processed due to a conflict.

410 Gone. It indicates that the requested resource is not available anymore. This error should be used when a resource was intentionally removed, although a 404 error could be returned.

411 Length Required. The request does not specify the content length which is a requirement for the requested resource.

412 Precondition Failed. The server does not accomplish with some pre-conditions that the user is requesting.

413 Request Entity Too Large. The request is to big to be processed.

414 Request-URI Too Long. The entered URI was too long to be processed.

415 Unsupported Media Type. The request does not specify none type of media. For instance, the client specifies the requested resource as image/svg+xml format, but the server does not find a resource with that format.

417 Expectation Failed. The server could not meet the requirements in the request headers.

422 Unprocessable Entity. The request was valid but the server was unable to attend it due to some semantic errors.

423 Locked. The resource which is being accessing is locked.

424 Failed Dependency. The request failed due to previous failed requests.

426 Upgrade Required. The client should be changed to a different protocol, for instance to TLS/1.0.

5xx Server Errors.

500 Internal Server Error. It is a generic error message and it’s returned when there is not a more specific error.

501 Not Implemented. The server neither recognizes the HTTP request method nor have the ability to complete the request.

502 Bad Gateway. The server was working as a gateway or proxy and it received an invalid response from the downstream server.

503 Service Unavailable. The server is not currently available (due to an overload or because it’s in maintenance). Generally, this error is temporal.

504 Gateway Timeout. The server did not receive a response in time.

505 HTTP Version Not Supported. The server does not support the HTTP protocol version used by the request.

Transparent PNGs in Internet Explorer 6

Easy fix for the transparent png issue in IE.

It’s true that I’ve decided to do not bother me to make the things work for Internet Explorer 6 and/or lower, always there is the need to attend client’s requests for the worst web browser ever. In this case, to to the problem witn transparency in PNG images.

To fix this bug we should download this file. After uncompress it we should include the iepngfix.htc and blank.gif files in your web server, then edit the iepngfix.htc file to indicate where you uploaded the blank.gif file. Also, we can read the iepngfix.html page to check how to use it ;-).

With this tool we can fix both the images in and the background images used with CSS; to do that we should add the below line in our css:

1
behavior: url(iepngfix.htc);

Keep on mind to set the right url to the iepngfix.htc file.

If we wish to make the tag to respect the transparent background in IE, we should add:

1
2
3
img{
  behavior: url(iepngfix.htc);
}

If we have a css element with a background image, we should add the behavior to it, for instance if we have a class named .logo, we should add:

1
2
3
4
.logo{
  background: url(images/logo.png) no-repeat left top;
  behavior: url(iepngfix.htc);
}

Well, that’s it! ๐Ÿ™‚

What is new in Symfony 1.3 / 1.4

At the end of this month it goes out the last release of Symfony and here we will review what are the new news. If you have already used 1.2 version you will notice a couple of improvements have been added.

Between the new functionalities, the most highlighted are:

Mailer

Symfony 1.3/1.4 comes with a new integrated mailer based on SwiftMailer 4.1. And, to send an email is as easy as we show below using the composeAndSend() method:

1
2
3
4
5
6
<?php
public function executeSendEmail()
{
    $this->getMailer()->composeAndSend('from@example.com', 'to@example.com', 'Subject', 'Body');
}
?>

If you need more flexibility and you need to attach a file, you can use the compose() method and then send it:

1
2
3
4
5
6
7
8
9
10
<?php
public function executeSendEmail()
{
    $message = $this->getMailer()
        ->compose('from@example.com', 'to@example.com', 'Subject', 'Body')
        ->attach(Swift_Attachment::fromPath('/path/to/a/file.zip'));
   
    $this->getMailer()->send($message);
}
?>

Swift Mailer is a great and powerful library, and if you want to know more about it you can check its documentation.

Security

In these versions when you use the generate:app command, the security is already actived by default. The escaping_strategy value is already activated by default, but you can deactivate it with the –escaping-strategy option. Also, for the csrf_secret option, the framework already comes with a random generated keyword and you can change it in the setting.yml configuration file.

Widgets

Labels by default: When a label is auto-generated from the field name, the label is defined without the _id suffix (if it has it). For instance, for the client_id field name, the generated label will be ‘client’ now (it was client_id before).

sfWidgetFormInputText: Now the sfWidgetFormInput class is abstract, and the text input fields should be created with sfWidgetFormInputText.

Forms

sfForm::useFileds(): This new method remove all the form fields, except those passed as argument. This ease the fields visualization in the form view without the need of make an unset() of the unwanted fields. For instance, when we add a new field in the base form, this one do not appear automatically in the form view at least we add it explicitly as an argument of this method:

1
2
3
4
5
6
7
8
9
<?php
class ArticleForm extends BaseArticleForm
{
    public function configure()
    {
        $this->useFields(array('title', 'content'));
    }
}
?>

By default, the array is used to change the fields order; we can pass a second argument as a false value to deactivate this automatic sort.

sfForm::getEmbeddedForm($name): Now we can access a particular embedded form using the getEmbeddedForm() method.

Autoloaders

All the Symfony’s autoloaders are case-insensitive now, since PHP is case-insensitive as well.

Default ORM

Symfony 1.3/1.4 comes with Doctrine as its default ORM.
If we want to use Propel as ORM, we should use the –orm=Propel option:

1
:$ php symfony generate:project foo --orm=Propel

And if we want to do not use Doctrine neither Propel, we can use the –orm=none option:

1
:$ php symfony generate:project foo --orm=none

These are the most highlighted features to me :D. There are a lot more improvements related to widgets, validators, routing, and much more CLI task as well.

MySQL: Backup and Restoring

In this post we will see how to make a MySQL backup and how to restore it.

If you are a web developer and even more if you programm with PHP surely you know that the most used database engine is MySQL. Of course, as a good developer you should know that is a golden rule to make and keep backups of your databases. Here we’ll see how to do it easily.

Back up from command line (using mysqldump)

We can backup our database using the mysqldump command, which connects with the database and generates a SQL dump file. This file has all the needed SQL queries to restore the database:

1
user@unix:~$ mysqldump --opt -u[uname] -p[pass] [dbname] > [backupfile.sql]

Where [uname] is the MySQL username, [pass] the user’s password, [dbname] is the database name, [backupfile.sql] is the output file name, and [–opt] are mysqldump options.

For instance, if we want to backup a database named ‘myBlog’ with a ‘root’ as username and the ‘mypass’ passowrd, and store the backup in a file called ‘myBlog_backup.sql’, we should run:

1
user@unix:~$ mysqldump -uroot -pmypass myBlog > myBlog_backup.sql

With mysqldump we can specify which tables we want to backup, for instance if we want to backup the ‘users’ and ‘posts’ tables, we should run:

1
user@unix:~$ mysqldump -uroot -pmypass myBlog users posts > myBlog2_backup.sql

Furthermore if we need to backup more than one database we can use the –databases option:

1
user@unix:~$ mysqldump -uroot -pmypass --databases myBlog car_shop clients > manydb_backup.sql

And also if we want to backup all the databases in MySQL we can use the –all-databases option:

1
user@unix:~$ mysqldump -uroot -pmypass --all-databases > alldb_backup.sql

Other utils options for mysqldump are:
–add-drop-table: Adds a DROP TABLE sentence before of each CREATE TABLE sentence in the dump.
–no-data: Backs up only the database structure with no data.
–add-locks: Adds the LOCK TABLES and UNLOCK TABLES sentences.

Back up whith compression

If our database is huge enough, we could want to compress the output with the following command:

1
user@unix:~$ mysqldump -u[uname] -p[pass] [dbname] | gzip -9 > [backupfile.sql.gz]

And to uncompress:

1
user@unix:~$ gunzip [backupfile.sql.gz]

Restoring the databases

Above we backed up a database called myBlog in a myBlog_backup.sql file. To restore it we should run the below commands:

1
user@unix:~$ mysql -u[uname] -p[pass] [db_to_restore] < [myBlog_backup.sql]

If we have compressed the dump:

1
user@unix:~$ gunzip < [backupfile.sql.gz] | mysql -u[uname] -p[pass] [dbname]

If we need to restore an existing database, we should run the mysqlimport command:

1
user@unix:~$ mysqlimport -u[uname] -p[pass] [dbname] [backupfile.sql]

That is. I hope it’s helful.