CodeIgniter 4 provides wonderful database insert functionality for web developers.

CodeIgniter 4 is like a magic wand for web developers. With just a few flicks, you can create databases, tables, and insert rows like a pro. It’s like being the conductor of a symphony, and every note plays in perfect harmony. Just a few tweaks here and there, and voila! Your masterpiece is ready to be unveiled. 🎩πŸͺ„

πŸ› οΈ Setting up the Database

To start with various database operations in CodeIgniter 4, you need a database. Here’s how you can set it up:

  1. Open XAMPP and click on phpMyAdmin for MySQL.
  2. Create a new database.
  3. Create a new table within the database.

| Field | Type |

| ———– | ——- |
| Name | VARCHAR |

| Email | VARCHAR |

| Status | VARCHAR |

πŸ–₯️ Configuring CodeIgniter 4 with the Database

Once your database is set up, you need to configure CodeIgniter 4 to use this database.

  • Go to app/config/database.php.
  • Set the database username, password, and name.
public $default = [
	'DSN'      => '',
	'hostname' => 'localhost',
	'username' => 'DB_man',
	'password' => 'your_password',
	'database' => 'myDB',
	...
];

πŸŽ›οΈ Accessing the Database in the Controller

Now, let’s access the configured database in your controller.

$db = \Config\Database::connect();

βž• Inserting a Row into the Database

To insert a new row into the database table, you can use the following query:

$query = "INSERT INTO users (name, email, status) VALUES ('My CI', 'myci@example.com', 'active')";
$result = $db->query($query);

πŸ” Verifying the Insertion

After executing the insert query, it’s important to verify if the operation was successful.

  • Check the number of affected rows to ensure that the insert operation was successful.
  • Verify the inserted data in the database to confirm the insert operation.
$affectedRows = $db->affectedRows();

Output:
1 row inserted successfully!

With these steps, the insert operation is done successfully in CodeIgniter 4.

About the Author

About the Channel:

Share the Post:
en_GBEN_GB