How can I create a CRUD with Codeigniter using SQLite? - php

I'm starting a new project where I want to use Codeigniter with SQLite. I searched information about this and I managed to conect and get data from my SQLite database but I have no idea of how can I create a CRUD for a table with this, I'm trying to do it the same way I did in the past with MySQL buy it is not working.
Here is what I did:
config/database.php
$db['default'] = array(
'dsn' => '',
'hostname' => '',
'username' => '',
'password' => '',
'database' => APPPATH.'/database/Pasapalabra.sqlite',
'dbdriver' => 'sqlite3',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
config/autoload.php
$autoload['libraries'] = array('database');
models/modelo_prueba.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class modelo_prueba extends CI_Model {
public function getTestData() {
return $this->db->get('preguntas')->result();
}
}
?>
controllers/Welcome.php
public function __construct() {
parent::__construct();
$this->load->library("grocery_CRUD");
}
public function prueba() {
$this->load->model('modelo_prueba');
$dataSet = $this->modelo_prueba->getTestData();
$this->load->view('data_view', [
'dataSet' => $dataSet
]);
}
views/data_view.php
<h4>Lets test the data</h4>
<?php
if($dataSet) {
foreach($dataSet as $dataItem) {
echo $dataItem->definicion . "<hr>";
}
}
?>
<h5>done!</h5>
This worked for me, it shows correctly all data in 'preguntas' database, but now I'm trying to create a CRUD just like I usually do with MySQL and it's working, it shows a database error.
The only thing that I have changed from the code of above is Welcome.php
public function prueba() {
$crud = new Grocery_CRUD();
$crud->set_table('preguntas');
$output = $crud->render();
$this->load->view("example.php", $output);
}
The error that is shown in the screen is the following:
A PHP Error was encountered
Severity: Warning
Message: SQLite3::query(): Unable to prepare statement: 1, near "SHOW": syntax error
Filename: sqlite3/sqlite3_driver.php
Line Number: 129
Backtrace:
File: C:\xampp\htdocs\Pasapalabra_Isidro\application\models\Grocery_crud_model.php
Line: 436
Function: query
File: C:\xampp\htdocs\Pasapalabra_Isidro\application\libraries\Grocery_CRUD.php
Line: 48
Function: get_field_types_basic_table
File: C:\xampp\htdocs\Pasapalabra_Isidro\application\libraries\Grocery_CRUD.php
Line: 1567
Function: get_field_types
File: C:\xampp\htdocs\Pasapalabra_Isidro\application\libraries\Grocery_CRUD.php
Line: 4507
Function: showList
File: C:\xampp\htdocs\Pasapalabra_Isidro\application\controllers\Welcome.php
Line: 38
Function: render
File: C:\xampp\htdocs\Pasapalabra_Isidro\index.php
Line: 315
Function: require_once
A Database Error Occurred
Error Number: 0
not an error
SHOW COLUMNS FROM `preguntas`
Filename: C:/xampp/htdocs/Pasapalabra_Isidro/system/database/DB_driver.php
Line Number: 691
Anyone knows what is happening? There isn't any error with the database connection because the previous code worked, but it's like Grocery CRUD can't create a CRUD of an SQLite.
I'm working with Codeigniter 3.1.4 and I created the SQLite database with SQLite Manager (Firefox) 0.8.3.1
Thank you for your answers.

Hi I have found solution from grocery crud form post with works with sqlite3 you have to modify Grocery curd library first copy sqlite3 model from this link
http://www.grocerycrud.com/forums/topic/651-suport-for-sqlite3/
this model extending grocery_crud_model, just include grocery_crud_model in your sqlite model.
in grocery crud library find grocery_crud_model, where it is loading this model just replace with grocery_crud_sqlite3, and you are done. it will work perfect.
just remember you have to modify these lines manually on each update in future.

Related

CakePHP - cake bake all error (says missing $default in database.php, but it is present)

I am trying to bake all with cake bake all, but it returns all sorts of errors. It says that default in database.php cannot be found, but in reality it is present in the file, also, few days ago I baked few models etc and it worked fine. Here is the output:
C:\wamp64\www\WarehouseManagementApp\app\Console>cake bake all
Warning Error: Use of undefined constant TESTS - assumed ‘TESTS’ (this will throw an Error in a future version of PHP) in [C:\wamp64\www\WarehouseManagementApp\lib\Cake\Console\TaskCollection.php, line 94]
Welcome to CakePHP v2.10.19 Console
App : Console
Path: C:\wamp64\www\WarehouseManagementApp\app\Console\
Bake All
Warning Error: include_once(C:\wamp64\www\WarehouseManagementApp\app\Console\Config\database.php): failed to open stream: No such file or directory in [C:\wamp64\www\WarehouseManagementApp\lib\Cake\Model\ConnectionManager.php, line 67]
Warning Error: include_once(): Failed opening ‘C:\wamp64\www\WarehouseManagementApp\app\Console\Config\database.php’ for inclusion (include_path=‘C:\wamp64\www\WarehouseManagementApp\lib;.;C:\php\pear’) in [C:\wamp64\www\WarehouseManagementApp\lib\Cake\Model\ConnectionManager.php, line 67]
Error: The datasource configuration “default” was not found in database.php
#0 C:\wamp64\www\WarehouseManagementApp\lib\Cake\Model\ConnectionManager.php(91): ConnectionManager::_getConnectionObject(‘default’)
#1 C:\wamp64\www\WarehouseManagementApp\lib\Cake\Console\Command\Task\ModelTask.php(956): ConnectionManager::getDataSource(‘default’)
#2 C:\wamp64\www\WarehouseManagementApp\lib\Cake\Console\Command\Task\ModelTask.php(893): ModelTask->getAllTables(‘default’)
#3 C:\wamp64\www\WarehouseManagementApp\lib\Cake\Console\Command\Task\ModelTask.php(983): ModelTask->listAll(‘default’)
#4 C:\wamp64\www\WarehouseManagementApp\lib\Cake\Console\Command\BakeShell.php(150): ModelTask->getName(‘default’)
#5 C:\wamp64\www\WarehouseManagementApp\lib\Cake\Console\Shell.php(459): BakeShell->all()
#6 C:\wamp64\www\WarehouseManagementApp\lib\Cake\Console\ShellDispatcher.php(222): Shell->runCommand(‘all’, Array)
#7 C:\wamp64\www\WarehouseManagementApp\lib\Cake\Console\ShellDispatcher.php(66): ShellDispatcher->dispatch()
#8 C:\wamp64\www\WarehouseManagementApp\app\Console\cake.php(47): ShellDispatcher::run(Array)
#9 {main}
Also, here is my database.php file:
class DATABASE_CONFIG {
public $default = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'root',
'password' => '',
'database' => 'modules',
'prefix' => '',
// ‘encoding’ => ‘utf8’,
);
public $test = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'user',
'password' => 'password',
'database' => 'test_database_name',
'prefix' => '',
//'encoding' => 'utf8',
);
}
Look at the include errors, they tell you that your database.php file cannot be found, and if you look at the path, you see that it looks in the Console/Config folder, which is of course the wrong location.
That is because the shell will use the current working directory as the application path, so either run the console from within your app folder, ie Console\cake bake all, or use the -app parameter to pass the path to your app folder:
cake bake all -app "C:\wamp64\www\WarehouseManagementApp\app"
The cake shell tells you about that too (cake --help), and shows you the relevant paths.
See also
Cookbook > Shells, Tasks & Console Tools

Codeigniter 4 possible to assign db_name(Database.php) in a variable or any other option

We want to connect one of too many databases as a default.
as per user requriment so we want take a database name in a variable or Global variable.
we are unable to use any variable in Database.php file
so guys help me for this problem.
view code here Codeigniter 4.0.0
It has been a while since I tried to do "weird" things like attempting to assign dynamic variables in configuration files so I'm not entirely sure if CodeIgniter supports it. However, even if it does, I would suggest using the function designed for these sort of things:
https://codeigniter4.github.io/userguide/database/connecting.html#connecting-with-custom-settings
$custom = [
'DSN' => '',
'hostname' => 'localhost',
'username' => '',
'password' => '',
'database' => '',
'DBDriver' => 'MySQLi',
'DBPrefix' => '',
'pConnect' => false,
'DBDebug' => (ENVIRONMENT !== 'production'),
'cacheOn' => false,
'cacheDir' => '',
'charset' => 'utf8',
'DBCollat' => 'utf8_general_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
];
$db = \Config\Database::connect($custom);
I suppose, since all else is the same except for database name you could also access the database configuration property for your default database and use $custom = array_replace($configDb, ['database' => $_SESSION['db_name']) to change out the database name. Obviously check that db_name exists and isn't empty and all that jazz. You could even put this entire logic in to a class with db_name as a constructor so you don't have to keep doing this all the time.
E.g. (untested):
namespace App\Config;
use InvalidArgumentException;
class DatabaseChooser extends \Config\Database
{
protected $dbName;
public function __construct(string $dbName = '')
{
$this->dbName = $dbName;
$config = $this->buildArr();
return parent::connect($config);
}
private function buildArr()
{
if (empty($this->dbName)) {
throw InvalidArgumentException('dbName cannot be empty');
}
$default = $this->defaultGroup;
if (property_exists($this, $default) && is_array($this->$default)) {
return array_replace($this->$default, ['database' => $this->dbName]);
} else {
throw new Exception('Invalid configuration.');
}
}
}
I'm sure you've considered it, but CI4 isn't exactly production ready afaik. To be honest, I'd be using something like Laravel, Lumen, or Symfony which already have an extensive and tested codebase, as well as many compatible third party packages.

Hosting CakePHP website with SQLite DB in OPENSHIFT

How to configure connection setting for sqlite database in Openshift?
Below code is my connection setup in database.php:
class DATABASE_CONFIG {
public $default = array(
'datasource' => 'Database/Sqlite',
'persistent' => false,
'database' => get_env('OPENSHIFT_DATA_DIR').'/database.sqlite',
'prefix' => ''
);
}
I have placed my sqlite db in path: "/var/lib/openshift/~/app-root/data"
When i access the website i receive the following error:
Parse error: syntax error, unexpected '(', expecting ')' in /var/lib/openshift/~/app-root/runtime/repo/app/Config/database.php on line 65
line 65: 'database' => get_env('OPENSHIFT_DATA_DIR').'/database.sqlite',
In PHP you can not use a function when declaring a class property.
If you must use that function you can write:
class DATABASE_CONFIG {
public $default = array(
'datasource' => 'Database/Sqlite',
'persistent' => false,
'prefix' => ''
);
function __construct() {
$this->default['database'] = get_env('OPENSHIFT_DATA_DIR').'/database.sqlite';
}
}

include_once: failed to open stream: No such file or directory in Cakephp 2.4.5

I am new to Cakephp, I am trying to install it. I extract everything and create the needed files/folders, now there is the following error:
Warning (2): include_once(C:\xampp\htdocs\TravelBuddy\app\Config\database.php): failed to open stream: No such file or directory [CORE\Cake\Model\ConnectionManager.php, line 67]
Warning (2): include_once() [function.include]: Failed opening 'C:\xampp\htdocs\TravelBuddy\app\Config\database.php' for inclusion (include_path='C:\xampp\htdocs\TravelBuddy\lib;.;C:\xampp\php\PEAR') [CORE\Cake\Model\ConnectionManager.php, line 67]
The file database.php does not exists. Do I have to create it?
Here is the code of ConnectionManager where the problem is:
protected static function _init() {
include_once APP . 'Config' . DS . 'database.php';
if (class_exists('DATABASE_CONFIG')) {
self::$config = new DATABASE_CONFIG();
}
self::$_init = true;
}
create inside: app/Config a file called database.php
now you need to configure your database connection like:
<?php
class DATABASE_CONFIG {
public $default = array (
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'yourusermysql',
'password' => 'passwordmysql',
'database' => 'nameofdatabase',
'prefix' => ''
);
public $test = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'user',
'password' => 'password',
'database' => 'test_database_name',
'prefix' => '',
//'encoding' => 'utf8',
);
}
?>
To avoid the given error you should do
if (class_exists('DATABASE_CONFIG', FALSE)) {
self::$config = new DATABASE_CONFIG();
}
i was struggling with same problem, but if the class didn't exist it should perform the remaining operation, and not giving me a fatal error.
http://www.php.net/manual/en/function.class-exists.php
Check and make sure the database.php file is committed in your git repo. Checkout the .gitignore file.

Making CakePHP work with SQL server 2008

I can call SQL server 2008 from PHP with Microsoft Drivers for PHP for SQL Server But as Sqlsvr driver class is needed to use CakePHP with SQL server 2008, I got the driver file from following repository.
However, when running my test cakephp with following database.php
<?php
class DATABASE_CONFIG {
var $default = array(
'driver' => 'sqlsvr',
'host' => 'localhost\EPHP',
'login' => 'sa',
'password' => 'xxxxxxx',
'database' => 'Blog',
);
}
?>
I got following error:
Fatal Error (256): ConnectionManager::loadDataSource - Unable to import DataSource class .DboSqlsvr [CORE\cake\libs\model\connection_manager.php, line 185]
Then I have read all the you-cannot-make-cakePHP-work-with-sql-2008 discussions. Is there any resolution by now?
UPDATE: Let me rephrase my question. I would appreciate if someone successfully made CakePHP work with SQL 2008 and tell me the procedure he followed to do that.
After some research, I found this article ( http://book.cakephp.org/view/1652/Plugin-DataSources-and-Datasource-Drivers). Basically, you can not place your driver file in the directory ( \cakephp\cake\libs\model\datasources\dbo) where the "factory" driver files are located. Instead you should place the driver file in following directory of your baked cake.
your-cake-application\plugins\your-plugin-name\models\datasources\dbo
And then you should change your database.php in config accordingly.
<?php
class DATABASE_CONFIG {
var $default = array(
'driver' => 'your-plugin-name.DboSqlsrv',
'host' => 'localhost\EPHP',
'login' => 'sa',
'password' => 'xxxxxxx',
'database' => 'Blog',
);
}
?>
After this, I could run my cakephp app.
Assuming you have the datasources in the folder app/model/datasource/dbo_sqlsrv.php load it like this:
<?php
class DATABASE_CONFIG {
var $default = array(
'datasource' => 'sqlsvr',
'host' => 'localhost\EPHP',
'login' => 'sa',
'password' => 'xxxxxxx',
'database' => 'Blog',
);
}
?>
The difference is in the 'driver' vs 'datasource' keyword

Categories