Codeigniter . December 25, 2022 . By Ankit Pathak

How to save MySQL queries into database in CodeIgniter

How to save MySQL queries into database in CodeIgniter

In CodeIgniter, you can use the Database Forge class to save all MySQL queries into the database and a file. Here’s an example of how you could do this:

  1. Load the Database Forge class: First, you’ll need to load the Database Forge class in your controller. You can do this by adding the following line at the top of your controller file:
$this->load->dbforge();
  1. Create a file: Next, you’ll need to create a file that will store the MySQL queries. You can do this using the following code:
$handle = fopen('/path/to/file.sql', 'w+');
  1. Get all tables: To get a list of all tables in the database, you can use the following code:
$tables = $this->db->list_tables();
  1. Loop through the tables: Now you can loop through the tables and generate the MySQL queries for each table. You can use the following code to generate the queries:
foreach ($tables as $table) {
$query = $this->db->query("SHOW CREATE TABLE `$table`");
$row = $query->row_array();
$sql = $row['Create Table'] . ";\n\n";
fwrite($handle, $sql);
}
  1. Close the file: Finally, you can close the file using the following code:
fclose($handle);

This will save all MySQL queries for the tables in the database to the file specified in step 2. You can also save the queries to the database by executing the queries using the $this->db->query() function.

  • Tag:
Chat on WhatsApp