Git Commands Cheat Sheet: 15 Essential Git Commands Every Developer Must Know (Beginner to Advanced Guide)

Git Commands Cheat Sheet: 15 Essential Git Commands Every Developer Must Know (Beginner to Advanced Guide)

Git Commands Cheat Sheet: 15 Essential Git Commands Every Developer Must Know

Git is one of the most powerful version control systems used by developers worldwide. Whether you’re working solo or collaborating in a team, mastering Git commands is essential for efficient code management.

In this guide, you’ll learn 15 essential Git commands with examples, helping you streamline your development workflow and avoid common mistakes.

🔹 1. git clone (Copy a Repository)

The git clone command is used to download a remote repository to your local machine.

git clone https://github.com/user/project.git

👉 This creates a complete local copy of the project, including all files and commit history.

🔹 2. git status (Check Repository Status)

This command shows the current state of your working directory.

git status

👉 It helps you identify:

  • Modified files
  • Staged files
  • Untracked files

🔹 3. git add (Stage Changes)

Before committing, you need to stage your changes.

git add file.txt

To add all files:

git add .

👉 Moves changes to the staging area.


🔹 4. git commit (Save Changes)

Commits save your staged changes with a message.

git commit -m "Added login feature"

👉 Think of it as creating a checkpoint in your project.


🔹 5. git push (Upload Code to Remote)

Push your local commits to a remote repository.

git push origin main

👉

  • origin = remote repository
  • main = branch name

🔹 6. git pull (Get Latest Code)

Fetches and merges the latest changes from the remote repository.

git pull origin main

👉 Best practice: Always pull before starting work to avoid conflicts.


🔹 7. git fetch (Download Changes Only)

Downloads changes without merging.

git fetch

👉 Useful for safely reviewing updates before applying them.


🔹 8. git branch (Manage Branches)

List all branches:

git branch

Create a new branch:

git branch feature-login

👉 Helps in working on features independently.


🔹 9. git checkout (Switch Branches)

Switch to another branch:

git checkout feature-login

Create and switch:

git checkout -b feature-login

👉 Used for navigation and restoring files.


🔹 10. git merge (Combine Branches)

Merge one branch into another.

git checkout main
git merge feature-login

👉 Integrates feature code into the main branch.


🔹 11. git log (View Commit History)

Shows commit history.

git log

Short version:

git log --oneline

👉 Helps track changes and history.


🔹 12. git diff (See Code Changes)

Displays differences between files.

git diff

👉 Useful for reviewing changes before committing.


🔹 13. git reset (Undo Staging)

Remove a file from staging area:

git reset file.txt

👉 Does not delete changes, only unstages them.


🔹 14. git stash (Save Work Temporarily)

Save unfinished work:

git stash

Restore it later:

git stash pop

👉 Perfect when switching branches without committing.


🔹 15. git remote (Manage Remote Repositories)

View remote repositories:

git remote -v

Add a new remote:

git remote add origin https://github.com/user/project.git

⚠️ Important Git Workflow Tip (Real-World Practice)

👉 Before pushing code:

  • Always pull from pencil_dev_env
  • Only push to basant_dev
  • Add proper tags when required

This ensures:

  • No merge conflicts
  • Clean collaboration
  • Proper version tracking

📌 Best Practices for Using Git

  • ✅ Commit frequently with meaningful messages
  • ✅ Pull before starting work
  • ✅ Use branches for new features
  • ✅ Avoid pushing directly to main
  • ✅ Use git fetch for safe updates
  • ✅ Keep your repository clean

🎯 Conclusion

Mastering these Git commands will significantly improve your development workflow. Whether you’re a beginner or an experienced developer, these commands form the foundation of efficient version control.

Start practicing today and make Git your best development companion 🚀

How to make dependent dropdown of state and district using cakephp2 form?

How to make dependent dropdown of state and district using cakephp2 form?

Creating dependent dropdowns in CakePHP 2 involves using AJAX to dynamically load data into the second dropdown based on the selection in the first. Here’s how you can implement a dependent dropdown of “State” and “District” in CakePHP 2:

Steps to Implement

1. Database Setup

Ensure you have two tables: states and districts, where districts has a state_id column to link districts to states.

Example schema:

  • states table:
    • id (Primary Key)
    • name (State Name)
  • districts table:
    • id (Primary Key)
    • name (District Name)
    • state_id (Foreign Key referencing states.id)

2. Controller Logic

In your controller (e.g., LocationsController):

  • Load states for the first dropdown.
  • Create an action to fetch districts based on the selected state.
class LocationsController extends AppController {
    public $uses = ['State', 'District'];

    public function index() {
        $states = $this->State->find('list', ['fields' => ['id', 'name']]);
        $this->set(compact('states'));
    }

    public function getDistricts($stateId = null) {
        $this->autoRender = false; // Disable view rendering
        if ($this->request->is('ajax') && $stateId) {
            $districts = $this->District->find('list', [
                'conditions' => ['District.state_id' => $stateId],
                'fields' => ['id', 'name']
            ]);
            echo json_encode($districts);
        }
    }
}

3. View

In your view file (e.g., index.ctp), create the dropdowns and include jQuery for AJAX:

echo $this->Form->create('Location', ['id' => 'LocationForm']);
echo $this->Form->input('state_id', [
    'type' => 'select',
    'options' => $states,
    'empty' => 'Select a State',
    'id' => 'StateDropdown'
]);
echo $this->Form->input('district_id', [
    'type' => 'select',
    'options' => [],
    'empty' => 'Select a District',
    'id' => 'DistrictDropdown'
]);
echo $this->Form->end();
?>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
    $('#StateDropdown').change(function() {
        var stateId = $(this).val();
        if (stateId) {
            $.ajax({
                url: "<?php echo $this->Html->url(['controller' => 'locations', 'action' => 'getDistricts']); ?>/" + stateId,
                type: "GET",
                dataType: "json",
                success: function(data) {
                    var districtDropdown = $('#DistrictDropdown');
                    districtDropdown.empty();
                    districtDropdown.append('<option value="">Select a District</option>');
                    $.each(data, function(key, value) {
                        districtDropdown.append('<option value="' + key + '">' + value + '</option>');
                    });
                },
                error: function() {
                    alert('Unable to fetch districts.');
                }
            });
        } else {
            $('#DistrictDropdown').empty().append('<option value="">Select a District</option>');
        }
    });
});
</script>

4. Routing

Ensure your routes are configured correctly for the AJAX request:

Router::connect('/locations/getDistricts/*', ['controller' => 'locations', 'action' => 'getDistricts']);

5. Result

  • The “State” dropdown is populated with data from the states table.
  • When a state is selected, an AJAX request fetches the corresponding districts and populates the “District” dropdown dynamically.

This approach ensures your dependent dropdown works efficiently in CakePHP 2.


Here is the SQL to create the districts table with the specified schema:

CREATE TABLE districts (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
state_id INT NOT NULL,
FOREIGN KEY (state_id) REFERENCES states(id) ON DELETE CASCADE ON UPDATE CASCADE
);

Insert Query for Indian Districts
INSERT INTO districts (name, state_id) VALUES
— Andhra Pradesh
(‘Anantapur’, 1),
(‘Chittoor’, 1),
(‘East Godavari’, 1),
(‘Guntur’, 1),
(‘Kadapa’, 1),

— Arunachal Pradesh
(‘Tawang’, 2),
(‘West Kameng’, 2),
(‘East Kameng’, 2),
(‘Papum Pare’, 2),
(‘Kurung Kumey’, 2),

— Assam
(‘Baksa’, 3),
(‘Barpeta’, 3),
(‘Biswanath’, 3),
(‘Bongaigaon’, 3),
(‘Cachar’, 3),

— Bihar
(‘Araria’, 4),
(‘Arwal’, 4),
(‘Aurangabad’, 4),
(‘Banka’, 4),
(‘Begusarai’, 4),

— Gujarat
(‘Ahmedabad’, 5),
(‘Amreli’, 5),
(‘Anand’, 5),
(‘Aravalli’, 5),
(‘Banaskantha’, 5),

— Karnataka
(‘Bagalkot’, 6),
(‘Ballari’, 6),
(‘Belagavi’, 6),
(‘Bengaluru Rural’, 6),
(‘Bengaluru Urban’, 6),

— Maharashtra
(‘Ahmednagar’, 7),
(‘Akola’, 7),
(‘Amravati’, 7),
(‘Aurangabad’, 7),
(‘Beed’, 7),

— Tamil Nadu
(‘Ariyalur’, 8),
(‘Chengalpattu’, 8),
(‘Chennai’, 8),
(‘Coimbatore’, 8),
(‘Cuddalore’, 8),

— Uttar Pradesh
(‘Agra’, 9),
(‘Aligarh’, 9),
(‘Allahabad’, 9),
(‘Ambedkar Nagar’, 9),
(‘Amethi’, 9),

— West Bengal
(‘Alipurduar’, 10),
(‘Bankura’, 10),
(‘Birbhum’, 10),
(‘Cooch Behar’, 10),
(‘Dakshin Dinajpur’, 10);

How to make id as auto increment in postgrey SQL?

How to make id as auto increment in postgrey SQL?

just add below code in column properties id Default input

Method: 1
nextval(‘form_submissions_id_seq’::regclass)

Method: 2 Via SQL Query

ALTER TABLE states
ADD COLUMN id SERIAL PRIMARY KEY;
Note: if you already have column id previous please delete before above running sql

How to Make ID as Auto Increment in PostgreSQL

When building a database in PostgreSQL, it’s common to want the ID field of a table to automatically increment whenever a new record is added. This ensures that each record has a unique identifier without needing manual input. Thankfully, PostgreSQL provides an easy and efficient way to set up auto-incrementing IDs using sequences.

In this blog, we’ll guide you through the process of creating an auto-incrementing ID field in PostgreSQL and explain how to use the nextval() function to set it up.

What Is an Auto Increment ID?

An auto-increment ID is a column in a database table where the value of the ID is automatically generated and incremented whenever a new row is inserted into the table. This is especially useful for primary keys, ensuring that each record has a unique identifier.

In PostgreSQL, auto-increment behavior is achieved by using a sequence. A sequence is a special kind of object in PostgreSQL that generates a series of unique numbers. You can associate this sequence with a table’s ID column so that the ID values are automatically generated in sequence.

How to Create Auto Increment ID in PostgreSQL

Follow these steps to create a table with an auto-incrementing ID in PostgreSQL.

1. Create a New Table with an Auto-Incrementing ID

The easiest way to create an auto-incrementing ID column in PostgreSQL is to use the SERIAL data type. This automatically creates an integer column that auto-increments with each insert.

CREATE TABLE form_submissions (
    id SERIAL PRIMARY KEY,
    name VARCHAR(100),
    email VARCHAR(100),
    submission_date TIMESTAMP
);

In the example above:

  • id SERIAL automatically creates a sequence called form_submissions_id_seq and assigns it to the id column.
  • Every time a new row is inserted, the id value will increment automatically.

2. Manually Setting the Auto-Increment ID Using nextval()

In some cases, you might prefer to manually set the sequence for the auto-increment functionality, or if you are working with an existing table that doesn’t have the SERIAL data type. Here’s how you can make an existing id column auto-increment using the nextval() function.

To do this, you would need to modify the DEFAULT value of the id column to use the nextval() function.

ALTER TABLE form_submissions
ALTER COLUMN id SET DEFAULT nextval('form_submissions_id_seq'::regclass);

Explanation:

  • nextval('form_submissions_id_seq'::regclass) is a function call that retrieves the next value from the sequence.
  • 'form_submissions_id_seq' is the name of the sequence that generates the values. When you use SERIAL, PostgreSQL automatically generates the sequence for you, and the sequence name is typically <table_name>_<column_name>_seq.
  • By setting the default value of the id column to nextval(), PostgreSQL will automatically assign a unique incremented value every time a new row is inserted into the table.

3. Inserting Data into the Table

Once the auto-increment feature is set up, you can insert data without needing to specify the id value, as PostgreSQL will take care of it automatically.

INSERT INTO form_submissions (name, email, submission_date)
VALUES ('John Doe', '[email protected]', '2025-01-28');

The id will be automatically generated, and in this case, it might be 1 for the first record.

4. Check the Table Data

To verify that the id is auto-incrementing correctly, you can run a simple SELECT query to see the data:

SELECT * FROM form_submissions;

You should see the id values starting from 1 and incrementing for each new row added.

Conclusion

Setting up an auto-increment ID in PostgreSQL is easy and helps ensure that every record in your table has a unique identifier. Whether you use the SERIAL data type for automatic setup or manually modify the column’s DEFAULT value with nextval(), PostgreSQL makes it simple to manage ID auto-incrementation.

Remember, to use the auto-increment functionality with an existing column, simply modify the column’s DEFAULT property to use the nextval() function as shown below:

ALTER TABLE form_submissions
ALTER COLUMN id SET DEFAULT nextval('form_submissions_id_seq'::regclass);

With these steps, you’ll be able to maintain a clean and consistent way of generating unique IDs for every new record added to your PostgreSQL database.

Happy coding!



How to Add Auto Increment to a Column in PostgreSQL ?

How to Add Auto Increment to a Column in PostgreSQL ?

Here’s a tailored post for your website using the requested keywords:


By Basant Mallick, Freelance PHP Developer in Delhi

As a freelance PHP developer in Delhi, I often work with PostgreSQL, a powerful open-source relational database system. One common requirement when designing database tables is to add an auto-increment feature for a column, usually for primary keys. In this guide, I’ll walk you through the process of setting up auto-increment in PostgreSQL.


What Is Auto Increment?

Auto-increment allows a database column to automatically generate a unique value for each row inserted into a table. In PostgreSQL, this is typically achieved using a SERIAL or IDENTITY column.


Steps to Add Auto Increment in PostgreSQL

1. Create a New Table with Auto Increment

If you’re creating a new table, you can define a column with the SERIAL or GENERATED AS IDENTITY type. Here’s an example:

CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    name VARCHAR(100) NOT NULL
);

The SERIAL keyword automatically creates a sequence behind the scenes and sets it up as the default value for the id column.


2. Modify an Existing Table to Add Auto Increment

If you need to add auto-increment functionality to an existing column, follow these steps:

  1. Add a Sequence: CREATE SEQUENCE users_id_seq;
  2. Set the Default Value Using the Sequence: ALTER TABLE users ALTER COLUMN id SET DEFAULT NEXTVAL('users_id_seq');
  3. Associate the Sequence with the Column: ALTER SEQUENCE users_id_seq OWNED BY users.id;
  4. Optional: Update Existing Values
    If your table already has data, make sure the sequence starts at the right value: SELECT SETVAL('users_id_seq', MAX(id)) FROM users;

3. Use GENERATED AS IDENTITY (PostgreSQL 10 and Later)

In newer PostgreSQL versions, the GENERATED AS IDENTITY feature is recommended as it offers more flexibility and is ANSI SQL-compliant. Example:

CREATE TABLE orders (
    order_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    product_name VARCHAR(255)
);

Why Choose PostgreSQL for Your Projects?

As a freelance PHP developer in Delhi, I recommend PostgreSQL for its reliability, scalability, and advanced features. Whether you’re building a small application or a complex enterprise system, PostgreSQL has the tools you need.


Need Help with Database Setup?

If you’re looking for an experienced freelance PHP developer in Delhi to handle your database design and development, feel free to contact me. Let’s bring your project to life with robust and efficient database solutions!


This post combines technical insights with SEO-friendly keywords to ensure better visibility and engagement on your website. Let me know if you’d like further optimizations!

Note: if you have already created table then just add below code in default coilumn in PgAdmin table properties

nextval('registration.license_list_log_id_seq'::regclass) 
How to add multiple images into database using mysql and php

How to add multiple images into database using mysql and php

// start multiple image

$stmt = $conn->prepare(“INSERT INTO cat_images (img_url, cat_id) VALUES (?, ?)”);
$stmt->bind_param(“si”, $imagePath, $cat_id);
$uploadedImages = $_FILES[‘images’];

$cat_id = $conn->insert_id;

foreach ($uploadedImages[‘name’] as $key => $value) {
$targetDir = “main-images/galleries/”;
$fileName = basename($uploadedImages[‘name’][$key]);
$targetFilePath = $targetDir . $fileName;
if (file_exists($targetFilePath)) {
echo “Sorry, file already exists.<br>”;
} else {
if (move_uploaded_file($uploadedImages[“tmp_name”][$key], $targetFilePath)) {
$imagePath = $targetFilePath;
$stmt->execute();
echo “The file ” . $fileName . ” has been uploaded successfully.<br>”;
} else {
echo “Sorry, there was an error uploading your file.<br>”;
}
}
}
$stmt->close();
$conn->close();

// end multiple image