[eluser]4ever[/eluser]
Solved!
Modul name: db_load.php
Creates database and table if one of these two does not exist.
Code:
<?php
class Db_load extends CI_Model {
/*
$dsn = 'dbdriver://username:password@hostname/database';
$this->load->database($dsn);
*/
function table_exists($table, $db) {
$tables = mysql_list_tables ($db);
while (list ($temp) = mysql_fetch_array ($tables)) if ($temp == $table) return TRUE;
return FALSE;
}
function generate_db(){
$database = "my_db";
$table_name = "table_name";
$this->load->database();
$CI =& get_instance();
$db =& $CI->db;
$mysql_link = mysql_connect( $db->hostname, $db->username, $db->password);
// $this->load->dbforge(); // DEPENDENCE: CI_DB_utility extends CI_DB_forge
// $this->load->dbutil(); // INIT: Database Utility Class
if ( !mysql_select_db($database) ):
$this->load->dbforge(); // LOAD
$this->load->dbutil();
$db_util_loaded = true;
if (!$this->dbforge->create_database('my_db')) die('Database not created!');
endif;
if ( !$this->table_exists($table_name, $database) ):
if ( !isset($db_util_loaded)): // LOAD
$this->load->dbforge();
$this->load->dbutil();
endif;
if ( !mysql_select_db($database) ) die("fail");
// DECLARING VALUES
$fields = array(
'users' => array(
'type' => 'VARCHAR',
'constraint' => '100',
),
'id' => array(
'type' => 'INT',
'constraint' => 5,
'unsigned' => TRUE,
'auto_increment' => TRUE
),
'title' => array(
'type' => 'VARCHAR',
'constraint' => '100',
),
'author' => array(
'type' =>'VARCHAR',
'constraint' => '100',
'default' => 'King of Town',
),
'desc' => array(
'type' => 'TEXT',
'null' => TRUE,
),
);
$this->dbforge->add_field($fields);
// ADD PRIMARY KEY
$this->dbforge->add_key('id', TRUE);
// NEXT WAYS
// $this->dbforge->add_key('blog_name'); // KEY
// $this->dbforge->add_key(array('blog_name', 'blog_label')); // KEY
// CREATING TABLE
$this->db->query('use ' . $database );
if ( !$this->dbforge->create_table($table_name)) die("Table not created!");
endif;
}
function get_all(){
// $q = $this->db->get("");
}
}
?>
Controller site Method:
Code:
function info(){
$this->load->model("db_load");
$this->db_load->generate_db();
$this->load->view("info_view");
}
Thanks to InsiteFX's help.
If you could check my code please... I hope it is all ok. Database and Table created to me.