Upgrade & Secure Your Future with DevOps, SRE, DevSecOps, MLOps!

We spend hours on Instagram and YouTube and waste money on coffee and fast food, but won’t spend 30 minutes a day learning skills to boost our careers.
Master in DevOps, SRE, DevSecOps & MLOps!

Learn from Guru Rajesh Kumar and double your salary in just one year.

Get Started Now!

SQLSTATE[HY000] [2002] Connection refused

Step-by-Step Solution:

  1. Locate the .env File:
    • The .env file is located in the root directory of your PHP or Laravel application. This file contains key-value pairs for environment-specific configurations.
  2. Edit the .env File:
    • Open the .env file in a text editor, such as VSCode or Sublime Text.
  3. Add the DB_SOCKET Configuration:
    • Inside the .env file, add the following line to specify the MySQL socket location: DB_SOCKET=/opt/lampp/var/mysql/mysql.sock
    • This line tells your application where to find the MySQL socket file, which resolves the connection refusal when using a local development environment like XAMPP.
  4. Verify Other Database Configuration:
    • Ensure that your database connection settings are correctly set. Below is an example of a full database configuration block in the .env file:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_user
DB_PASSWORD=your_database_password
DB_SOCKET=/opt/lampp/var/mysql/mysql.sock

5. Save the .env File:

  • After adding the socket configuration, save the .env file.

6. Clear Route, Cache, and Optimize the Application:

  • Once you’ve updated the .env file, it’s essential to clear and optimize the Laravel application’s cache, routes, and configuration. This will ensure your changes are reflected and improve the application’s performance. Run the following commands from your terminal:
php artisan config:cache        # Clear and cache the configuration files
php artisan route:cache         # Clear and cache the route files
php artisan cache:clear         # Clear the application's cache
php artisan optimize            # Optimize the application's performance

    Conclusion: By adding the DB_SOCKET line to your .env file, you can easily fix the Connection refused error caused by socket connection issues in local PHP environments like XAMPP. This simple change can save you a lot of troubleshooting time and get your PHP application connecting to MySQL without errors.

    Related Posts

    Subscribe
    Notify of
    guest
    0 Comments
    Oldest
    Newest Most Voted
    Inline Feedbacks
    View all comments
    0
    Would love your thoughts, please comment.x
    ()
    x
    Artificial Intelligence