CodeIgniter: Unknown column 'xxx' in 'field list' - codeigniter

Here's my exported BD table:
CREATE TABLE `hta_users` (
`id` int(11) NOT NULL auto_increment,
`nombre` varchar(100) collate utf8_spanish_ci NOT NULL,
`apellidos` varchar(255) collate utf8_spanish_ci NOT NULL,
`nif` varchar(10) collate utf8_spanish_ci NOT NULL,
`direccion` varchar(255) collate utf8_spanish_ci NOT NULL,
`cp` varchar(5) collate utf8_spanish_ci NOT NULL,
`poblacion` varchar(255) collate utf8_spanish_ci NOT NULL,
`provincia` int(2) NOT NULL,
`telefono` varchar(9) collate utf8_spanish_ci NOT NULL,
`edad` int(3) NOT NULL,
`retribucion` int(1) NOT NULL,
`entidad` varchar(4) collate utf8_spanish_ci NOT NULL,
`oficina` varchar(4) collate utf8_spanish_ci NOT NULL,
`dc` varchar(2) collate utf8_spanish_ci NOT NULL,
`cc` varchar(10) collate utf8_spanish_ci NOT NULL,
`centro` varchar(255) collate utf8_spanish_ci NOT NULL,
`email` varchar(255) collate utf8_spanish_ci NOT NULL,
`especialidad` int(2) NOT NULL,
`parent` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `nif` (`nif`,`email`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci AUTO_INCREMENT=1 ;
Here's my model function:
function add_user( $nombre, $apellidos, $nif, $direccion, $cp, $poblacion, $provincia, $telefono, $edad, $retribucion, $cc_entidad, $cc_oficina, $cc_dc, $cc_cc, $centro, $email, $especialidad, $parent )
{
$tbl = $this->db->dbprefix('users');
if( $retribucion == 1 )
{
$sql = array(
'nombre' => $nombre,
'apellidos' => $apellidos,
'nif' => $nif,
'direccion' => $this->db->escape($direccion),
'cp' => $cp,
'poblacion' => $poblacion,
'provincia' => $provincia,
'telefono' => $telefono,
'edad' => $edad,
'retribucion' => $retribucion,
'entidad' => $cc_entidad,
'oficina' => $cc_oficina,
'dc' => $cc_dc,
'cc' => $cc_cc,
'centro' => $centro,
'email' => $email,
'especialidad' => $especialidad,
'parent' => $parent
);
}
else
{
$sql = array(
'nombre' => $nombre,
'apellidos' => $apellidos,
'nif' => $nif,
'direccion' => $this->db->escape($direccion),
'cp' => $cp,
'poblacion' => $poblacion,
'provincia' => $provincia,
'telefono' => $telefono,
'edad' => $edad,
'retribucion' => $retribucion,
'centro' => $centro,
'email' => $email,
'especialidad' => $especialidad,
'parent' => $parent
);
}
$this->db->insert($tbl, $sql);
if( $this->db->affected_rows() == 0 ) return false;
else return true;
}
Here's my controller piece of code:
if( $this->users->add_user($nombre, $apellidos, $nif, $direccion, $cp, $poblacion, $provincia, $telefono, $edad, $retribucion, $cc_entidad, $cc_oficina, $cc_dc, $cc_cc, $centro, $email, $especialidad, $parent) )
{
$data['form_error'] = 'Se ha aƱadido al usuario.';
$data['module'] = 'registro';
$this->load->view('template', $data);
}
else
{
$data['form_error'] = 'Se ha producido un error al agregar al usuario a la BD.';
$data['module'] = 'registro';
$this->load->view('template', $data);
}
And that's the error i'm getting:
A Database Error Occurred
Error Number: 1054
Unknown column 'entidad' in 'field list'
INSERT INTO `hta_users` (`nombre`, `apellidos`, `nif`, `direccion`, `cp`, `poblacion`, `provincia`, `telefono`, `edad`, `retribucion`, `entidad`, `oficina`, `dc`, `cc`, `centro`, `email`, `especialidad`, `parent`) VALUES ('nombre', 'apellidos', '12345678Q', '\'elm st 666\'', '08008', 'Barcelona', '1', '666555666', '2', 1, '9999', '9999', '99', '9999999999', 'home', 'email#domain.com', '1', '0')
Can someone help? I don't know what's happening nor why... :/

Here is an article I wrote that will help you with debugging CodeIgniter ActiveRecord. Basically use $this->db->last_query() to see what ActiveRecord built your query to be and run it in phpMyAdmin to see if the query itself is valid.
There are a few other tips too, but from what I can see here everything looks fine.
Sneaky tip: you can use:
return !$this->db->affected_rows() == 0;
instead of:
if( $this->db->affected_rows() == 0 ) return false;
else return true;

Well, after some hours of harddebuggin' got it working... :P
Same database table structure.
My new model function:
function add_user( $user_data )
{
$tbl = $this->db->dbprefix('users');
$this->db->insert($tbl, $user_data);
return !$this->db->affected_rows() == 0;
}
My new controller piece of code:
$user_data = array(
'nombre' => $this->input->post('nombre'),
'apellidos' => $this->input->post('apellidos'),
'nif' => $this->input->post('nif'),
'direccion' => $this->db->escape($this->input->post('direccion')),
'cp' => $this->input->post('cp'),
'poblacion' => $this->input->post('poblacion'),
'provincia' => $this->input->post('provincia'),
'telefono' => $this->input->post('telefono'),
'edad' => $this->input->post('edad'),
'retribucion' => $this->input->post('retribucion'),
'entidad' => $this->input->post('cc_entidad'),
'oficina' => $this->input->post('cc_oficina'),
'dc' => $this->input->post('cc_dc'),
'cc' => $this->input->post('cc_cc'),
'centro' => $this->input->post('centro'),
'email' => $this->input->post('email'),
'especialidad' => $this->input->post('especialidad'),
'parent' => $this->session->userdata('parent')
);
// db adding
if( $this->users->add_user($user_data) )
{
// logged in!!
}
else
{
// grrr error!!
}
It looks much pretty now! :)
Hope this helps some lost souls to DO NOT construct the AR data array into the model, but the controller.

Related

Get Id file uploaded google drive job queue laravel

i am making an image storage function with laravel job queue via googledrive. i am trying to initialize and store my photo. It works with the code:
$filePut = file_get_contents($this->path);
Storage::cloud()->put($this->name, $filePut);
but i can't get the return id
i am changing to another method and here is my 2nd code:
public function handle(GoogleClient $googleDrive)
{
dd($googleDrive);
$driveService = new \Google_Service_Drive($googleDrive);
$fileMetadata = new \Google_Service_Drive_DriveFile([
'name' => $this->name,
]);
$file = $driveService->files->create($fileMetadata, [
'data' => file_get_contents($this->path),
'uploadType' => 'multipart',
'fields' => 'id',
]);
$driveService->getClient()->setUseBatch(true);
try {
$batch = $driveService->createBatch();
$userPermission = new \Google_Service_Drive_Permission([
'type' => 'anyone',
'role' => 'reader',
]);
$request = $driveService->permissions->create($file->id, $userPermission, ['fields' => 'id']);
$batch->add($request, 'user');
$results = $batch->execute();
} catch (\Exception $e) {
} finally {
$driveService->getClient()->setUseBatch(false);
}
I noticed the data received from dd($googleDrive) is no data :
App\Components\GoogleClient {#3225
#client: Google\Client {#3203
-auth: null
-http: null
-cache: null
-token: null
-config: array:29 [
"application_name" => ""
"base_path" => "https://www.googleapis.com"
"client_id" => ""
"client_secret" => ""
"credentials" => null
"scopes" => null
"quota_project" => null
"redirect_uri" => null
"state" => null
"developer_key" => ""
"use_application_default_credentials" => false
"signing_key" => null
"signing_algorithm" => null
"subject" => null
"hd" => ""
"prompt" => ""
"openid.realm" => ""
"include_granted_scopes" => null
"login_hint" => ""
"request_visible_actions" => ""
I try to store it before the queue then the $drivegoogle data I get is as follows:
Google\Client {#3146
-auth: null
-http: null
-cache: null
-token: array:6 [
"access_token" => "*************************************************************************************"
"expires_in" => "*************************************************************************************"
"scope" => "*************************************************************************************"
"token_type" => "*************************************************************************************"
"created" => "*************************************************************************************"
"refresh_token" => "*************************************************************************************"
]
-config: array:29 [
"application_name" => ""
"base_path" => "https://www.googleapis.com"
"client_id" => "*************************************************************************************"
"client_secret" => "*************************************************************************************"
"credentials" => null
"scopes" => null
"quota_project" => null
"redirect_uri" => null
"state" => null
"developer_key" => ""
"use_application_default_credentials" => false
"signing_key" => null
"signing_algorithm" => null
"subject" => null
"hd" => ""
"prompt" => ""
"openid.realm" => ""
"include_granted_scopes" => null
"login_hint" => ""
"request_visible_actions" =>
is there any workaround to get the id from the storage::put method, or is there another way to fix my current error, the error appears at new \Google_Service_Drive($googleDrive); constructor must be array or instance of Google\Client {"exception":"[object] (TypeError(code: 0): constructor must be array or instance of Google\\Client
$googleDrive = $googleDrive->getClient()

Reset index on table with Eloquent model

I am scratching my head to figure out why this legacy code supposedly will reset the indexes on a database table. Can you shed some light on it?
$employee = new Employee();
$employee->update([
'recruited' => 0,
'job_id' => null,
'job_start_date' => null,
'job_end_date' => null,
'interviewed' => 0
]);
There are a corresponding Eloquent model called Employee.
try to use :
DB::table('employees')->update([
'recruited' => 0,
'job_id' => null,
'job_start_date' => null,
'job_end_date' => null,
'interviewed' => 0
]);

Use sort order from TCA select to list items in fluid

In my TCA I use a select to an other table.
'modules' => [
'label' => 'LLL:EXT:myextension_module_table/Resources/Private/Language/locallang_db.xlf:tx_myextension_domain_model_semester.modules',
'config' => [
'type' => 'select',
'renderType' => 'selectMultipleSideBySide',
'enableMultiSelectFilterTextfield' => true,
'foreign_table' => 'tx_myextension_domain_model_module',
'minitems' => 1,
'maxitems' => 99,
],
],
Under "Selected Items" I can sort the items. Now I want to use this sort order in fluid. In database I see the right order 21,1,2,3,4,28. But in fluid the items are always sorted by uid.
Adding 'sortby' => 'sorting', with all needed changes doesn't solve my problem. In this case I can order records in list view. But I don't want this order. I want to show order from "Selected Items" in frontend.
In my ModuletableController.php I get the selected moduletable from Flexform.
/**
* action show
*
* #param \Vendor\Myextension\Domain\Model\Moduletable $moduletable
* #return void
*/
public function showAction(\Vendor\Myextension\Domain\Model\Moduletable $moduletable = NULL) {
if (is_null($moduletable)) {
$moduletable = $this->moduletableRepository->findByUid($this->settings['singleModuleTable']);
}
$this->view->assign('moduletable', $moduletable);
}
An in the template Show.html I loop through it.
<html xmlns:f="http://typo3.org/ns/TYPO3/Fluid/ViewHelpers">
<f:layout name="Default" />
<f:section name="main">
<h2>{moduletable.title}</h2>
<f:for each="{moduletable.semester}" as="semester">
<p>{semester.title}</p>
<f:for each="{semester.modules}" as="module">
<p{module.title}</p>
</f:for>
</f:for>
</f:section>
Solution is to use MM tables. Then sort order is set in TCA select field.
In TCA:
'modules' => [
'label' => 'LLL:EXT:myextension/Resources/Private/Language/locallang_db.xlf:tx_myextension_domain_model_semester.modules',
'config' => [
'type' => 'select',
'renderType' => 'selectMultipleSideBySide',
'enableMultiSelectFilterTextfield' => true,
'foreign_table' => 'tx_myextension_domain_model_module',
'foreign_sortby' => 'sorting',
'MM' => 'tx_myextension_semester_module_mm',
'minitems' => 1,
'maxitems' => 99,
],
],
In ext_tables.sql
CREATE TABLE tx_myextension_semester_module_mm (
uid_local int(11) unsigned DEFAULT '0' NOT NULL,
uid_foreign int(11) unsigned DEFAULT '0' NOT NULL,
sorting int(11) unsigned DEFAULT '0' NOT NULL,
sorting_foreign int(11) unsigned DEFAULT '0' NOT NULL,
KEY uid_local (uid_local),
KEY uid_foreign (uid_foreign)
);
How do you get the selected items in your Extbase controller? Maybe you can use this findByUidListOrderByList function here: http://blog.teamgeist-medien.de/2014/09/typo3-extbase-repository-find-by-multiple-uids-findbyuids.html#comment-90

laravel 5 issue with slashes in query

I am using Laravel 5 and I am facing issues with query when I have slashes(forward or backward)
publications table structure:
CREATE TABLE IF NOT EXISTS `publications` (
`id` bigint(20) NOT NULL,
`user_id` bigint(20) NOT NULL,
`title` varchar(512) NOT NULL,
`type` varchar(512) NOT NULL,
`company` varchar(512) NOT NULL,
`author` varchar(512) NOT NULL,
`firm` varchar(512) NOT NULL,
`address` text NOT NULL,
`sector_id` bigint(20) NOT NULL DEFAULT '0',
`date_from` timestamp NULL DEFAULT NULL,
`date_to` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`region_id` bigint(20) NOT NULL DEFAULT '0',
`file_name` varchar(512) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`created_by` bigint(20) NOT NULL,
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`updated_by` bigint(20) NOT NULL,
`is_active` tinyint(1) NOT NULL DEFAULT '1',
`category_id` bigint(20) NOT NULL,
`sub_category_id` bigint(20) NOT NULL,
`manually_verified` tinyint(1) NOT NULL DEFAULT '0'
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;
Data:
INSERT INTO `publications` (`id`, `user_id`, `title`, `type`, `company`, `author`, `firm`, `address`, `sector_id`, `date_from`, `date_to`, `region_id`, `file_name`, `created_at`, `created_by`, `updated_at`, `updated_by`, `is_active`, `category_id`, `sub_category_id`, `manually_verified`) VALUES
(3, 7, 'test publication 3', 'test 1', 'test 1', 'test author 1', 'test 1', 'test3', 1, '2015-06-09 11:54:18', '2015-06-29 18:30:00', 0, 'files/testing/testing.pdf', '2015-06-06 05:58:10', 7, '2015-06-13 03:31:45', 7, 0, 4, 1, 0),
(4, 7, 'test publication 4', 'test 2', 'test 2', 'test author 2', 'test 2', 'test2', 1, '2015-06-09 11:54:23', '2015-06-29 18:30:00', 0, 'test1.pdf', '2015-06-06 05:58:10', 7, '2015-06-05 23:58:10', 7, 1, 4, 1, 0),
(5, 7, 'test 5', 'test', 'test', 'test', 'test', 'test', 1, '2015-06-09 11:54:09', '2015-06-29 18:30:00', 0, 'files/Bugzilla-uermanual.pdf', '2015-06-06 05:58:10', 7, '2015-06-13 03:19:21', 7, 0, 4, 1, 1);
Laravel 5
$arr = array( 'file_paths' => Array ( 'files/testing/testing.pdf', 'files/Bugzilla-uermanual.pdf' ) );
Query
$this->publications
->where(['category_id'=>$search_cat_id])
->where(function ($query) use ($arr){
foreach ($arr['file_paths'] as $key=>$value){
$query->orWhere('file_name', DB::connection()->getPdo()->quote($value));
}
})
->get();
print_r($publications_records);
I don't get any result. If I execute the query which was generated by laravel it is getting executed.
Below is the query generated by Laravel and if I execute this in MySQL I get results.
select * from `publications`
where (`category_id` = 4) and
(`file_name` = 'files/testing/testing.pdf'
or `file_name` = 'files/Bugzilla-uermanual.pdf')
order by `id` desc
Try this:
$arr = ['files/testing/testing.pdf', 'files/Bugzilla-uermanual.pdf'];
$publications_records = $this->publications()
->where('category_id', $search_cat_id)
->where(function ($query) use ($arr){
foreach ($arr as $value){
$query->orWhere('file_name', $value);
}
})
->get();
dd($publications_records, DB:getQueryLog());
If the above code doesnt work. Please edit your question and paste the output

Add an auto_increment column in Magento setup script without using SQL

Previously I asked how to ALTER TABLE in Magento setup script without using SQL. There, Ivan gave an excellent answer which I still refer to even now.
However I have yet to discover how to use Varien_Db_Ddl_Table::addColumn() to specify an auto_increment column. I think it has something to do with an option called identity but so far have had no luck.
Is this even possible or is that functionality incomplete?
One can create an autoincrement column like that (at least since Magento 1.6, maybe even earlier):
/** #var $table Varien_Db_Ddl_Table */
$table->addColumn( 'id', Varien_Db_Ddl_Table::TYPE_INTEGER, null, array(
'auto_increment' => true,
'unsigned' => true,
'nullable' => false,
'primary' => true,
), 'ID' );
Instead of "auto_increment", one may also use the keyword "identity".
I think that's something that hasn't been implemented yet.
If you look at the source to addColumn, you can see it looks for a identity/auto_increment option and sets an IDENTITY attribute on the internal column representation.
#File: lib/Varien/Db/Ddl/Table.php
if (!empty($options['identity']) || !empty($options['auto_increment'])) {
$identity = true;
}
$upperName = strtoupper($name);
$this->_columns[$upperName] = array(
'COLUMN_NAME' => $name,
'COLUMN_TYPE' => $type,
'COLUMN_POSITION' => $position,
'DATA_TYPE' => $type,
'DEFAULT' => $default,
'NULLABLE' => $nullable,
'LENGTH' => $length,
'SCALE' => $scale,
'PRECISION' => $precision,
'UNSIGNED' => $unsigned,
'PRIMARY' => $primary,
'PRIMARY_POSITION' => $primaryPosition,
'IDENTITY' => $identity
);
However, if you look at the createTable method on the connection object
#File: lib/Varien/Db/Adapter/Pdo/Mysql.php
public function createTable(Varien_Db_Ddl_Table $table)
{
$sqlFragment = array_merge(
$this->_getColumnsDefinition($table),
$this->_getIndexesDefinition($table),
$this->_getForeignKeysDefinition($table)
);
$tableOptions = $this->_getOptionsDefination($table);
$sql = sprintf("CREATE TABLE %s (\n%s\n) %s",
$this->quoteIdentifier($table->getName()),
implode(",\n", $sqlFragment),
implode(" ", $tableOptions));
return $this->query($sql);
}
you can see _getColumnsDefinition, _getIndexesDefinition, and _getForeignKeysDefinition are used to create a CREATE SQL fragment. None of these methods make any reference to identity or auto_increment, nor do they appear to generate any sql that would create an auto increment.
The only possible candidates in this class are
/**
* Autoincrement for bind value
*
* #var int
*/
protected $_bindIncrement = 0;
which is used to control the increment number for a PDO bound parameter (nothing to do with auto_increment).
There's also a mention of auto_increment here
protected function _getOptionsDefination(Varien_Db_Ddl_Table $table)
{
$definition = array();
$tableProps = array(
'type' => 'ENGINE=%s',
'checksum' => 'CHECKSUM=%d',
'auto_increment' => 'AUTO_INCREMENT=%d',
'avg_row_length' => 'AVG_ROW_LENGTH=%d',
'comment' => 'COMMENT=\'%s\'',
'max_rows' => 'MAX_ROWS=%d',
'min_rows' => 'MIN_ROWS=%d',
'delay_key_write' => 'DELAY_KEY_WRITE=%d',
'row_format' => 'row_format=%s',
'charset' => 'charset=%s',
'collate' => 'COLLATE=%s'
);
foreach ($tableProps as $key => $mask) {
$v = $table->getOption($key);
if (!is_null($v)) {
$definition[] = sprintf($mask, $v);
}
}
return $definition;
}
but this is used to process options set on the table. This auto_increment controls the table AUTO_INCREMENT options, which can be used to control which integer an AUTO_INCREMENT starts at.

Resources