Codeigniter doesn`t save sessions on database - mysql

I`m trying to save my session on database without success. I already set CI config, autoload and nothing works.
On my controller
$session_data = array(
'session_id' => session_id(),
'ip_address' => $this->input->ip_address(),
'user_agent' => $this->input->user_agent(),
'last_activity' => substr($_SERVER['HTTP_USER_AGENT'], 0, 120),
'user_data' => 'logged'
);
$this->session->set_userdata('ci_sessions', $session_data);
Autoload
$autoload['libraries'] = array('database','session');
$autoload['drivers'] = array('session');
Config
$config['encryption_key'] = 'wqf35MV437ytPyGweGHH24775zK8u7uD';
$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_sessions';
$config['sess_encrypt_cookie'] = FALSE;
$config['sess_expiration'] = 8640;
$config['sess_use_database'] = TRUE;
$config['sess_table_name'] = 'ci_sessions';
$config['sess_expire_on_close'] = TRUE;
$config['sess_save_path'] = NULL;
$config['sess_match_ip'] = TRUE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
And default ci_session table on MYSQL
CREATE TABLE IF NOT EXISTS 'ci_sessions' (
session_id varchar(40) DEFAULT '0' NOT NULL,
ip_address varchar(45) DEFAULT '0' NOT NULL,
user_agent varchar(120) NOT NULL,
last_activity int(10) unsigned DEFAULT 0 NOT NULL,
user_data text NOT NULL,
PRIMARY KEY (session_id),
KEY 'last_activity_idx' ('last_activity')
);

You have mixed your CI2 session config up with CI3 session config.
Session Database User Guide CI3
If your using CodeIgniter 3 If you would like to save session to database
change
$config['sess_driver'] = 'files';
$config['sess_save_path'] = NULL;
To
$config['sess_driver'] = 'database';
// This will be your table name for session
$config['sess_save_path'] = 'ci_sessions';
$config['sess_expiration'] = 7200;
$config['sess_match_ip'] = TRUE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
And
CREATE TABLE IF NOT EXISTS `ci_sessions` (
`id` varchar(40) NOT NULL,
`ip_address` varchar(45) NOT NULL,
`timestamp` int(10) unsigned DEFAULT 0 NOT NULL,
`data` blob NOT NULL,
KEY `ci_sessions_timestamp` (`timestamp`)
);
Then I would autoload session
$autoload['libraries'] = array('session');

Related

SQL query is not inserting records in table when column values are equal

I am trying to execute this query but it is not working. whenever i try to put same equal values to any two or more input variables out of total 8, the SQL query does not execute.
php file:
include './config.php';
$counter = 0;
// these are my total 8 input variables
$INDEX_NUMBER = "43385";
$STATION_NAME = "NA";
$YEAR = "2020";
$MONTH = "12";
$DATE = "18";
$Ir = "3";
$RAIN_24HOURS_ACTUAL = "NA";
$RTRTRTRT = "NA";
$sql_rain_2 ="INSERT INTO `only_rainfall_2020` (`INDEX_NUMBER`, `STATION_NAME`, `YEAR`, `MONTH`, `DATE`, `Ir`, `DAILY`, `SEASONALLY_SYNOP`) SELECT * FROM (SELECT '$INDEX_NUMBER', '$STATION_NAME', '$YEAR', '$MONTH', '$DATE', '$Ir', '$RAIN_24HOURS_ACTUAL', '$RTRTRTRT') AS tmp WHERE NOT EXISTS (SELECT `INDEX_NUMBER`, `STATION_NAME`, `YEAR`, `MONTH`, `DATE`, `Ir`, `DAILY`, `SEASONALLY_SYNOP` FROM `only_rainfall_2020` WHERE `INDEX_NUMBER` = '$INDEX_NUMBER' AND `STATION_NAME` = '$STATION_NAME' AND `YEAR` = '$YEAR' AND `MONTH` = '$MONTH' AND `DATE` = '$DATE' AND `Ir` = '$Ir' AND `DAILY` = '$RAIN_24HOURS_ACTUAL' AND `SEASONALLY_SYNOP` = '$RTRTRTRT') LIMIT 1";
if (mysqli_query($conn, $sql_rain_2)) {
$counter++;
}
$array = array("rain1"=>$counter, "rain2"=>"yogi");
echo json_encode($array);
mysql table:
CREATE TABLE `only_rainfall_2020` (
`SERIAL` int(11) NOT NULL,
`SUB_DIVISION_NUMBER` varchar(2) NOT NULL,
`SUB_DIVISION_NAME` varchar(20) NOT NULL,
`INDEX_NUMBER` varchar(5) NOT NULL,
`STATION_NAME` varchar(30) NOT NULL,
`YEAR` varchar(4) NOT NULL,
`MONTH` varchar(2) NOT NULL,
`DATE` varchar(2) NOT NULL,
`Ir` varchar(2) NOT NULL,
`DAILY` varchar(7) NOT NULL,
`MONTHLY` varchar(7) NOT NULL,
`SEASONALLY_SYNOP` varchar(7) NOT NULL,
`SEASONALLY_CALCULATE` varchar(7) NOT NULL,
`ANNUALLY` varchar(7) NOT NULL,
`COMMENT` varchar(50) NOT NULL,
`MANUALLY_EDIT_VALUE` varchar(14) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `only_rainfall_2020`
ADD PRIMARY KEY (`SERIAL`);
ALTER TABLE `only_rainfall_2020`
MODIFY `SERIAL` int(11) NOT NULL AUTO_INCREMENT;
COMMIT;
Please point out my mistake.
After many attempts i could not find my mistake.
let me clear it again:
I am trying to insert data for 8 columns into a table which has total 16 columns. In my table, one column is for serial number which is auto incremental, seven are blank columns and eight are the columns in which i am inserting data. I am leaving seven blank column for future work with no default values. the condition for inserting data for these eight column: any row should not exist with same data for these eight columns which i am going to insert. when i give different values for these eight columns than query is successful and data inserted but when i put same values for any two or more columns than query does not execute.
this is successful:
$INDEX_NUMBER = "43385";
$STATION_NAME = "DELHI";
$YEAR = "2020";
$MONTH = "12";
$DATE = "18";
$Ir = "3";
$RAIN_24HOURS_ACTUAL = "NA";
$RTRTRTRT = "20";
But when i put any two values same the query does not execute.
Failed with error: (#1060 - Duplicate column name 'NA')
$INDEX_NUMBER = "43385";
$STATION_NAME = "NA";
$YEAR = "2020";
$MONTH = "12";
$DATE = "18";
$Ir = "3";
$RAIN_24HOURS_ACTUAL = "NA";
$RTRTRTRT = "NA";
And yes there are warnings for like:
Warning: #1364 Field 'SUB_DIVISION_NUMBER' doesn't have a default value
But i will add values in these columns later.

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '7775-683756' for key 'camera_from_to_unique'

This is the table layout:
CREATE TABLE camera
(
entity_id VARCHAR(50) PRIMARY KEY NOT NULL,
area_type INT(11) NOT NULL,
type INT(11),
`from` INT(11),
`to` INT(11),
severity INT(11) NOT NULL,
description VARCHAR(255),
additional_information VARCHAR(255),
location POINT NOT NULL,
reported_at DATETIME NOT NULL,
road_id INT(11) NOT NULL,
ugc TINYINT(1) COMMENT 'user generated content',
event INT(11),
advice VARCHAR(255),
updated_at DATETIME NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL
);
CREATE UNIQUE INDEX camera_from_to_unique ON camera (`from`, `to`);
And this is the query:
INSERT INTO `camera`
(
`entity_id`,
`area_type`,
`type`,
`from`,
`to`,
`severity`,
`description`,
`additional_information`,
`location`,
`reported_at`,
`road_id`,
`ugc`,
`event`,
`advice`
) VALUES (
:id_28,
:area_type_28,
:type_28,
:from_28,
:to_28,
:severity_28,
:description_28,
:additional_information_28,
POINT(:position_x_28, :position_y_28),
:reported_at_28,
:road_id_28,
:ugc_28,
:event_28,
:advice_28
) ON DUPLICATE KEY UPDATE
`entity_id` = :id_28,
`area_type` = :area_type_28,
`type` = :type_28,
`from` = :from_28,
`to` = :to_28,
`severity` = :severity_28,
`description` = :advice_28,
`additional_information` = :description_28,
`location` = POINT(:position_x_28, :position_y_28),
`reported_at` = :reported_at_28,
`road_id` = :road_id_28,
`ugc` = :ugc_28,
`event` = :event_28,
`advice` = :advice_28
And these are the binded parameters:
array (
'id_28' => 'NLSIT0020843410',
'area_type_28' => 1,
'type_28' => 46,
'from_28' => 7775,
'to_28' => 683756,
'severity_28' => 80,
'description_28' => '',
'additional_information_28' => 'Tussen knp. Hattemerbroek en Zwolle-Noord',
'position_x_28' => 6.032483,
'position_y_28' => 52.490729000000002,
'reported_at_28' => '2017-01-06 16:43:00',
'road_id_28' => 621453,
'ugc_28' => 0,
'event_28' => 1072,
'advice_28' => '',
)
I thought that because my from and to field are both in the same unique index in my table, the ON DUPLICATE KEY UPDATE would be triggered, but apparently that is not the case.
Could someone please explain why my ON DUPLICATE KEY UPDATE is not triggered so the data gets updated instead of this mysql error?
The duplicate key update part of the insert is being activated. However the attempt to update the row instead of inserting is failing. Because of this.
) ON DUPLICATE KEY UPDATE
`entity_id` = :id_28,
`area_type` = :area_type_28,
`type` = :type_28,
`from` = :from_28, /* this one */
`to` = :to_28, /* and this one */
YOu are trying to force mysql to have the same values for the from and to columns that triggered the duplicate. You need to remove those two columns from the ON DUPLICATE KEY clause. So we have
ON DUPLICATE KEY UPDATE
`entity_id` = :id_28,
`area_type` = :area_type_28,
`type` = :type_28,
`severity` = :severity_28,
`description` = :advice_28,
`additional_information` = :description_28,
`location` = POINT(:position_x_28, :position_y_28),
`reported_at` = :reported_at_28,
`road_id` = :road_id_28,
`ugc` = :ugc_28,
`event` = :event_28,
`advice` = :advice_28

Zend update() gives out application error even with correct parameters

I am using Zend_File_Transfer_Adapter_HTTP() to upload a file (image) and then with Application_Model_DbTable_User() to update the users mysql table with the corresponding path of the file .
This is the action in the controller :
public function profileAction() {
$form = new Application_Form_Updateprofile();
$users = new Application_Model_DbTable_User();
$session = new Zend_Auth_Storage_Session();
$adapter = new Zend_File_Transfer_Adapter_HTTP();
$loggedUser = $session->read()->username;
$this->view->form = $form;
if ($this->getRequest()->isPost()) {
$adapter->setDestination('ProfilePhotos');
$filename = pathinfo($form->image->getFileName());
$adapter->addFilter('Rename', uniqid() . '.' . $filename['extension']);
if (!$adapter->receive()) {
$messages = $adapter->getMessages();
echo implode("\n", $messages);
} else {
$userProfilePhoto = $adapter->getFileName('image');
$users->UpdateProfilePic($loggedUser, $userProfilePhoto);
}
}
}
This is the function UpdateProfilePic() in the Zend_File_Transfer_Adapter_HTTP() :
public function UpdateProfilePic($username, $img_address) {
$bind = array("profile_pic" => $img_address);
$where = "username = $username";
$this->_db->update($this->_name, $bind, $where);
}
Var_dump($username,$img_address,$bind,$where)
Output :
$img_address - string(31) "ProfilePhotos\5429294234ebe.gif"
$username - string(7) "Tiberiu"
$bind - array(1) { ["profile_pic"]=> string(31) "ProfilePhotos\5429294234ebe.gif" }
$where - string(18) "username = Tiberiu"
Users table :
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(255) NOT NULL,
`username` varchar(30) NOT NULL,
`password` varchar(15) DEFAULT NULL,
`profile_pic` varchar(50) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1
This is my first attempt on Zend_File_Upload and although the file transfer is a success it won't update the users table and I can't figure out why , I've checked the manual and I think I'm feeding the correct parameters to the update() action.
The mistake was in UpdateProfilePic() function in my db class .
It should be :
$where = "`username` = '$username'";
Instead of :
$where = "`username` = $username";

Converting custom sql query in to a dataprovider yii?

I'm trying to convert the following query in to a dataprovider, so it can be displayed within a CGridView. I have tried using a CArrayDataProvider, but have not had any luck so far, any help would be much appreciated!
Here is the query
public function getTeamsByLevelIdAndCompetitionId($levelId, $competitionId)
{
$query = "SELECT t.*,
(SELECT COUNT(*)
FROM tbl_competition_teams ct
WHERE ct.team = t.id
AND ct.competition = :competitionId) AS 'inCompetition'
FROM tbl_teams t
WHERE t.level = :levelId";
$params = array(
'levelId' => $levelId,
'competitionId' => $competitionId
);
$result = array();
$teams = $this->findAllBySQL($query, $params);
return $teams;
}
This is how I tried to make it in to a CArrayDataProvider:
public function getTeamsByLevelIdAndCompetitionId($levelId, $competitionId)
{
$rawData = Yii::app()->db->createCommand("SELECT t.*,
(SELECT COUNT(*)
FROM tbl_competition_teams ct
WHERE ct.team = t.id
AND ct.competition = :competitionId) AS 'inCompetition'
FROM tbl_teams t
WHERE t.level = :levelId")->queryAll();
$params = array(
'levelId' => $levelId,
'competitionId' => $competitionId
);
return new CArrayDataProvider($rawData, array(
'id'=>'id',
'sort'=>array(
'attributes'=>array(
'id', 'title', 'club', 'level', 'inCompetition',
),
),
));
}
but that gives me the error "CDbCommand failed to execute the SQL statement: SQLSTATE[HY093]: Invalid parameter number: no parameters were bound."
Here is my teams table
CREATE TABLE `tbl_teams` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(35) NOT NULL DEFAULT '',
`level` int(10) unsigned DEFAULT NULL,
`club` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=2952 ;
and my competition teams table
CREATE TABLE `tbl_competition_teams` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`competition` int(10) unsigned NOT NULL DEFAULT '0',
`team` int(10) unsigned NOT NULL DEFAULT '0',
`seasonId` int(11) NOT NULL DEFAULT '3',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=126320 ;
Thanks a million in advance for any advice!
Maybe the problem is you queryAll() execute the query. At this momento you are not assigning the values to you parameters
$rawData = Yii::app()->db->createCommand("SELECT t.*,
(SELECT COUNT(*)
FROM tbl_competition_teams ct
WHERE ct.team = t.id
AND ct.competition = $competitionId) AS 'inCompetition'
FROM tbl_teams t
WHERE t.level = $levelId")->queryAll();
also you can try to rewrite your query.
$query = "SELECT t.*,
(SELECT COUNT(*)
FROM tbl_competition_teams ct
WHERE ct.team = t.id
AND ct.competition = :competitionId) AS 'inCompetition'
FROM tbl_teams t
WHERE t.level = :levelId";
$command= Yii::app()->db->createCommand($query);
$command->bindValue(':levelId', $levelId);
$command->bindValue(':competitionId', $competitionId);
$rawData = $command->queryAll();

SQLSTATE[HY000]: General error: 1366 Incorrect integer value:

$order = new Application_Model_DbTable_Order();
$orderno = $order->select()
->from($order, 'orderno')
->where('memberid = ?', $userid)
->order('orderno DESC')
->limit(1, 0);
SQLSTATE[HY000]: General error: 1366 Incorrect integer value: 'SELECT ordertable.orderno FROM ordertable WHERE (memberid = '30') ORDER BY orderno DESC LIMIT 1' for column 'orderno' at row 1
Got this error and am wondering if there is anything wrong with my code, because I have searched everywhere for the cause but don't seem to find any help.
#SQL code for Ordertable#
`orderno` int(5) NOT NULL AUTO_INCREMENT,
`memberid` int(5) DEFAULT NULL,
PRIMARY KEY (`orderno`)
#SQL code for Item#
`itemid` int(5) NOT NULL AUTO_INCREMENT,
`image` varchar(100) NOT NULL,
`itemname` varchar(30) DEFAULT NULL,
`description` varchar(100) DEFAULT NULL,
`itemtype` varchar(20) DEFAULT NULL,
PRIMARY KEY (`itemid`)
#SQL code for Orderdetail#
`orderdetailno` int(5) NOT NULL AUTO_INCREMENT,
`orderno` int(5) NOT NULL,
`itemid` int(5) NOT NULL,
`unitcost` decimal(6,2) DEFAULT NULL,
PRIMARY KEY (`orderdetailno`),
KEY `orderno` (`orderno`),
KEY `itemid` (`itemid`)
This is my sql code if it helps I'm using MySQL.
$request = new Zend_Session_Namespace('cart');
$auth = Zend_Auth::getInstance();
$user = $auth->getIdentity();
$userid = $user->userid;
$order = new Application_Model_DbTable_Order();
$itemdb = new Application_Model_DbTable_Item();
$orderdetail = new Application_Model_DbTable_Orderdetail();
$data = array ('memberid' => $userid);
$order->insert($data);
$orderno = $order->select()
->from($order, 'orderno')
->where('memberid = ?', $userid)
->order('orderno DESC')
->limit(1, 0);
foreach ($request->array as $var)
{
$unitprice = $itemdb->select()
->from('$itemdb', 'unitcost')
->where('itemid = ?', $var);
$newArray = array('orderno' => $orderno,
'itemid' => $var,
'unitcost' => $unitprice, );
$orderdetail->insert($newArray);
}
Any guidance will be very much appreciated.
Per https://stackoverflow.com/a/8882396/1432614, run
SELECT ##GLOBAL.sql_mode;
SELECT ##SESSION.sql_mode;
and if either include STRICT_TRANS_TABLES, remove it from the setting.
For example:
SET ##GLOBAL.sql_mode= 'NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
The reason you are getting that error is because you are attempting to use a Zend_Db_Select object as a value in your INSERT statement.
$orderno = $order->select()
->from($order, 'orderno')
->where('memberid = ?', $userid)
->order('orderno DESC')
->limit(1, 0);
And then inside the foreach loop:
$newArray = array('orderno' => $orderno, // <-- this becomes a SELECT statment
'itemid' => $var,
'unitcost' => $unitprice, );
$orderdetail->insert($newArray); // attempting to insert a select statement
You should execute the $orderno statement and fetch() the result if you want to use it in an insert statement:
$ordernum = $orderno->query()->fetch();
$newArray = array('orderno' => $ordernum,
'itemid' => $var,
'unitcost' => $unitprice, );
$orderDetail->insert($newArray);