Tuesday, January 7, 2025

How to get the auto incremented id after adding the data in mysql

 In one of the project we were working on, we had a situation, where we need to add a record to the table of the database. The added record id is auto incremented in database. This id needs to added to another table with some more data. Now the issue here is how to get the auto increamented value of the previous table. 

In PHP, you can retrieve the auto-incremented ID generated by a INSERT operation in a MySQL database using the mysqli_insert_id() function. Here's how you can do it:

Example Code

<?php // Database connection $servername = "localhost"; $username = "root"; $password = ""; $database = "your_database"; $conn = new mysqli($servername, $username, $password, $database); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Insert query $sql = "INSERT INTO your_table (column1, column2) VALUES ('value1', 'value2')"; if ($conn->query($sql) === TRUE) { // Get the last inserted ID $last_id = $conn->insert_id; echo "New record created successfully. Last inserted ID is: " . $last_id; } else { echo "Error: " . $sql . "<br>" . $conn->error; } // Close connection $conn->close(); ?>

Explanation

  1. Database Connection: Establishes a connection to the MySQL database using mysqli.
  2. Insert Query: Executes an INSERT statement.
  3. Retrieve Last ID:
    • $conn->insert_id retrieves the auto-incremented ID of the last inserted record.
  4. Error Handling: Checks if the query was successful before attempting to retrieve the ID.
  5. Close Connection: Always close the database connection after performing operations.

Notes

  • Make sure the column is defined as AUTO_INCREMENT in the table schema.
  • If you're using a database abstraction library like PDO, you can use PDO::lastInsertId() instead.
  • Ensure proper escaping or use prepared statements to prevent SQL injection. For example:

$stmt = $conn->prepare("INSERT INTO your_table (column1, column2) VALUES (?, ?)"); $stmt->bind_param("ss", $value1, $value2); $stmt->execute(); $last_id = $stmt->insert_id; $stmt->close();

This approach is more secure and should be preferred for user input.

In Laravel, retrieving the auto-incremented ID after inserting a record is straightforward, especially if you are using Eloquent or the query builder.
Using Eloquent
If you are using Eloquent, the save method or the create method automatically returns the auto-incremented ID of the record.

// Example 1: Using save()
$model = new YourModel();
$model->column1 = 'value1';
$model->column2 = 'value2';
$model->save();
$lastInsertedId = $model->id; // Retrieves the auto-incremented ID
// Example 2: Using create()
$model = YourModel::create([
'column1' => 'value1',
'column2' => 'value2',
]);
$lastInsertedId = $model->id; // Retrieves the auto-incremented ID

Using Query Builder

If you are using Laravel's query builder, you can use the insertGetId method, which inserts a record and directly returns the auto-incremented ID.

$lastInsertedId = DB::table('your_table')->insertGetId([
'column1' => 'value1',
'column2' => 'value2',
]);
echo "The last inserted ID is: " . $lastInsertedId;

Explanation
Eloquent Approach:
  • $model->save(): Saves the record to the database and updates the $model->id property with the auto-incremented ID.
  • YourModel::create(): Inserts the record and returns the model instance with the id property set.
  • Ensure that the $fillable property in your model is defined for mass assignment in create().
Query Builder Approach:
  • insertGetId: Inserts the record and directly returns the ID of the inserted record.
Notes
  • Eloquent automatically manages timestamps (created_at, updated_at) if the table has them, so you don't need to handle them manually.
  • If using create(), make sure the YourModel class has the $fillable or $guarded property defined:
  • For additional security, always validate and sanitize input data before inserting it into the database. Use Laravel's validation mechanisms.
protected $fillable = ['column1', 'column2'];

Monday, January 6, 2025

How to check and change innodb buffer pool size in mysql database

 The InnoDB buffer pool size in MySQL determines how much memory is allocated to store frequently accessed data and indexes. To check and change it, follow these steps:

1. Check Current InnoDB Buffer Pool Size

    Log in to MySQL
        mysql -u root -p
   Run the Following Query
        SHOW VARIABLES LIKE 'innodb_buffer_pool_size';

This will display the current size in bytes.


2. Change InnoDB Buffer Pool Size

    a. Edit the MySQL Configuration File

The InnoDB buffer pool size is set in the MySQL configuration file (my.cnf or my.ini).

  1. Open the configuration file in a text editor (e.g., nano on Ubuntu):

    sudo nano /etc/mysql/my.cnf
  2. Locate the [mysqld] section and add or update the following line:

    innodb_buffer_pool_size = 1G

    Replace 1G with the desired size (e.g., 512M, 2G, etc.).

    • Best Practice: Set the buffer pool size to around 70-80% of your server's total RAM if MySQL is the primary application on the server.
    b. Save and Exit

    Save the changes and exit the text editor.

    c. Restart MySQL Service

        Restart MySQL to apply the changes:

        sudo systemctl restart mysql

3. Verify the Change

Log in to MySQL again and run the query to confirm the new buffer pool size:

        SHOW VARIABLES LIKE 'innodb_buffer_pool_size';

Additional Notes
  • For servers with large memory, consider splitting the buffer pool into multiple instances:

    innodb_buffer_pool_instances = 4

    This setting improves performance for systems with a high buffer pool size.

  • If MySQL fails to restart, check the error log for details:

    sudo tail -n 50 /var/log/mysql/error.log

Saturday, January 4, 2025

Setting of Auto backup of Mysql database in a laravel project

 When we work on any database project, it's always good to set up autoback of the database on daily basis. We can set up a cron job for backing up a MySQL database in a Laravel project, follow these steps:

1. Create a Laravel Artisan Command

  1. Run the following command to create a custom Artisan command:

    php artisan make:command BackupDatabase
  2. Open the generated file in app/Console/Commands/BackupDatabase.php and update its content:

    <?php
    namespace App\Console\Commands; use Illuminate\Console\Command; use Illuminate\Support\Facades\Storage; class BackupDatabase extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'backup:database'; /** * The console command description. * * @var string */ protected $description = 'Backup the MySQL database'; /** * Execute the console command. */ public function handle() { $dbName = env('DB_DATABASE'); $dbUser = env('DB_USERNAME'); $dbPassword = env('DB_PASSWORD'); $dbHost = env('DB_HOST', '127.0.0.1'); $backupPath = storage_path('app/backups/' . date('Y-m-d_H-i-s') . '_backup.sql'); // Ensure the backup directory exists Storage::makeDirectory('backups'); $command = sprintf( 'mysqldump -u%s -p%s -h%s %s > %s', escapeshellarg($dbUser), escapeshellarg($dbPassword), escapeshellarg($dbHost), escapeshellarg($dbName), escapeshellarg($backupPath) ); $result = null; $output = null; exec($command, $output, $result); if ($result === 0) { $this->info('Database backup created successfully: ' . $backupPath); } else { $this->error('Failed to create database backup.'); } } }

2. Schedule the Command in Laravel

  1. Open the app/Console/Kernel.php file.

  2. Register the new command in the schedule method:

    protected function schedule(Schedule $schedule)
    { $schedule->command('backup:database')->dailyAt('02:00'); }

    This schedules the backup to run daily at 2:00 AM. Adjust the time as needed.


3. Set Up the Cron Job

  1. Open the cron jobs configuration file:

    crontab -e
  2. Add the following line to execute Laravel's scheduler every minute:

    * * * * * php /path-to-your-laravel-project/artisan schedule:run >> /dev/null 2>&1

    Replace /path-to-your-laravel-project with the actual path to your Laravel application.


4. Verify Backup Files

  1. The backups will be stored in the storage/app/backups directory.
  2. Ensure the directory is writable by the web server and the Laravel application.

5. Additional Suggestions

  • Compression: Modify the command to compress the backup:

    $command = sprintf(
    'mysqldump -u%s -p%s -h%s %s | gzip > %s.gz', escapeshellarg($dbUser), escapeshellarg($dbPassword), escapeshellarg($dbHost), escapeshellarg($dbName), escapeshellarg($backupPath) );
  • Cloud Storage: Use Laravel's filesystem to store the backups on S3, Google Cloud Storage, etc.

Friday, October 25, 2024

AI usage in CRM applications

AI has become instrumental in CRM applications, enhancing customer experience, automating processes, and improving decision-making. Here are key areas where AI can make a difference in CRM systems:

  1. Personalized Customer Interactions:

    • AI can analyze customer data (purchase history, browsing behavior, preferences) to deliver tailored product recommendations and targeted content.
    • It enables predictive personalization, where the system anticipates what customers may need or want before they ask.
  2. Predictive Sales Analytics:

    • AI algorithms can predict customer behavior patterns, such as purchase likelihood, churn risk, and product interests.
    • Sales teams can leverage this data to prioritize leads, forecast sales, and allocate resources more effectively.
  3. Customer Support and Chatbots:

    • AI-powered chatbots provide 24/7 customer support, answering common questions and guiding customers through processes.
    • NLP (Natural Language Processing) enables bots to understand complex queries and resolve issues faster, improving customer satisfaction.
  4. Sentiment Analysis:

    • AI can analyze customer interactions (emails, chat, social media) to gauge sentiment, allowing companies to understand how customers feel about products or services.
    • This helps in proactive engagement, like reaching out to unsatisfied customers or rewarding loyal ones.
  5. Automation of Routine Tasks:

    • AI automates repetitive CRM tasks, such as data entry, lead qualification, and follow-up scheduling, freeing up sales reps to focus on high-value activities.
    • This improves productivity and reduces human error.
  6. Lead Scoring and Qualification:

    • AI assesses leads based on interaction history, engagement patterns, and behavioral data, helping prioritize those most likely to convert.
    • It enables dynamic lead scoring, where the value of leads can adjust in real-time as new data comes in.
  7. Customer Segmentation:

    • AI can cluster customers into segments based on demographics, behavior, or other attributes for more targeted marketing and sales strategies.
    • This enables a better focus on different customer types and preferences, enhancing campaign effectiveness.
  8. Voice and Speech Recognition:

    • In call centers, AI-driven voice analysis can recognize tone, speed, and keywords to understand customer intent and sentiment.
    • This data is useful for tailoring responses and guiding agents during calls.
  9. Anomaly Detection and Fraud Prevention:

    • AI algorithms can detect unusual patterns that indicate potential fraud or customer account anomalies, enhancing security.
    • This protects customer data and ensures trust in the CRM system.
  10. Enhanced Data Analysis and Reporting:

    • AI provides advanced analytics and reporting capabilities, turning vast data into actionable insights with ease.
    • It enables CRM applications to suggest optimal actions, which can then be leveraged by teams to enhance customer journeys.

By integrating AI into CRM systems, businesses can deliver a smarter, faster, and more personalized customer experience while optimizing operations and strategic decision-making.

Wednesday, September 25, 2024

Running Web Application Locally

 To create a local-only web application that can still receive patches from outside your network, you can set up a configuration like this:

1. Host the Web Application Locally

  • Local Network Hosting: Host the web application on a server or computer accessible only within your internal network. Restrict access to local IP ranges only to ensure that it cannot be accessed from outside.
  • Firewall Settings: Set up firewall rules to block external traffic to the app’s port(s). This will prevent any outside access to the app.

2. Set Up an Update Server

To update the local app, you can have a server outside your local network (e.g., on a cloud server) to serve as the patch/update server.

  • Patch Server: Host a separate, secure server with patch files and updates. You could use a cloud service or a remote server with restricted access.
  • Patch Files: Store updates in a version-controlled system (such as Git) on the patch server. Keep patch files in a directory that your local server can access for downloading.

3. Use a Secure Script to Fetch Updates

  • Secure Fetch Script: Set up a script on your local server to periodically check the patch server for new updates. The script could be a cron job (Linux) or Task Scheduler task (Windows) to check for patches and apply them.
  • VPN or SSH: Establish a secure VPN or SSH tunnel for the local server to connect to the patch server. This allows only authorized local machines to access patches, maintaining network security.
  • Checksum or Signature Verification: Validate the integrity and authenticity of patch files by verifying checksums or using digital signatures.

4. Apply Patches to the Local App

  • Once updates are downloaded, automate the patch application to minimize downtime and ensure the app is always up to date. Ensure you have a rollback mechanism to prevent issues in case of failed updates.

Example Setup

  1. Patch Server: Git server (on cloud), hosting versioned code and patches.
  2. Local Server:
    • Fetch script to connect to Git server for updates.
    • Firewall rules allow access only to the update server’s IP or VPN connection.
    • Apply updates on schedule or manually as needed.

This approach gives you a local-only app with a controlled update process through an external server, ensuring privacy and minimizing external access to your network.