I am having some issues with sessions.
In the first function queue, I save the session entries I can print this out from this function, so I can see its being set correctly.
In the function remove, I try and save this entries session into a variable and I get the error that entries is an undefined index.
Does anyone have any ideas what I am doing wrong here?
function queue()
{
session_start();
$status = 'Awaiting Moderation';
$channel = '1';
// Find all entries in 'Gallery' channel with 'Awaiting Moderation' status
$this->EE->db->select('entry_id')
->from('exp_channel_titles')
->where('status', $status)
->where('channel_id', $channel);
$query = $this->EE->db->get();
$entries = $query->result_array();
$entries_count = count($entries);
// Set count
$_SESSION['entries_count'] = $entries_count;
// If entries found
if ($entries_count > 0)
{
// Flatten entry ids array
$entriesFlat = array();
array_walk_recursive($entries, function($a) use (&$entriesFlat) { $entriesFlat[] = $a; });
$entriesSerial = serialize($entriesFlat);
// Save in session
$_SESSION['entries'] = $entriesSerial;
}
}
function remove()
{
session_start();
// Get session data + save into variable
$entries = $_SESSION['entries'];
}
You can only have one session and it should be at the top of your file.
Since your using codeigniter why not use codeigniter session and then autoload library and then you can do code like below.
$this->session->set_userdata('entries_count', $entries_count);
To Get Data
$this->session->userdata('entries_count');
And
$this->session->set_userdata('entries', $entriesSerial);
To Get Data
$this->session->userdata('entries');
// Example
if ($this->session->userdata('entries') > 0)
{
User Guide
CI2 http://www.codeigniter.com/userguide2/libraries/sessions.html
CI3: http://www.codeigniter.com/user_guide/libraries/sessions.html
http://www.codeigniter.com/docs
1st of all, there's not need to declare 'session' again at 'remove()' function..
2ndly to set session contents you have to write :
$this->session->set_userdata('entries_count', $entries_count);
Instead of
$_SESSION['entries'] = $entriesSerial;
Save it in session
To get session contents you've to write:
$entries_count = $this->session->userdata('entries_count');
Get session data + save into variable
Then you can write the condition like:
if ($entries_count > 0) {
}
Similarly, you've to write
$this->session->set_userdata('entries', $entriesSerial);
To save in session instead of
$_SESSION['entries'] = $entriesSerial;
And
$entries = $this->session->userdata('entries');
To Get session data + save into variable
Related
i have a problem that when i get data from other api and want if same title wont save to api. Each time getting data from the api is 20 and want to save it to the database without duplicate. Please help me. Thank you very much!!!
public function getTitle($title){
$title = $this->posts->where('title', $title)->get();
return $title;
}
public function getApi(Request $request){
$url = "https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=87384f1c2fe94e11a76b2f6ff11b337f";
$data = Http::get($url);
$item = json_decode($data->body());
$i = collect($item->articles);
$limit = $i->take(20); // take limited 5 items
$decode = json_decode($limit);
foreach($decode as $post){
$ite = (array)$post;
$hi = $this->getTitle($ite['title']);
dd($ite['title'], $hi);
if($ite['title']==$hi){
dd('not save');
}
else{
dd('save');
}
//dd($hi, $ite['title']);
// create post
$dataPost = [
'title'=>$ite['title'],
'description'=>$ite['description'],
'content'=>$ite['content'],
'topic_id'=>'1',
'post_type'=>$request->type,
'user_id'=>'1',
'enable'=>'1',
'feature_image_path'=>$ite['urlToImage']
];
//dd($dataPost);
//$this->posts->create($dataPost);
}
return redirect()->route('posts.index');
}
You can use first or create for saving data in database if title name is new. using firstOrNew you dont have to use any other conditions
for example:-
$this->posts->firstOrCreate(
['title' => $ite['title']],
['description'=>$ite['description'],
'content'=>$ite['content'],
'topic_id'=>'1',
'post_type'=>$request->type,
'user_id'=>'1',
'enable'=>'1',
'feature_image_path'=>$ite['urlToImage']]);
firstOrNew:-
It tries to find a model matching the attributes you pass in the first parameter. If a model is not found, it automatically creates and saves a new Model after applying any attributes passed in the second parameter
From docs
If any records exist that match your query's constraints, you may use
the exists and doesntExist methods
if($this->posts->where('title', $title)->doesntExist())
{
// save
} else {
// not save
}
I have an HTML page which is has one user input and one button. After clicking on the button, we can fetch other data related to that user from oracle database. i have defined my code in a seperate php page( index2.php ) which looks like below:-
<?php
class logAgent
{
const CONFIG_FILENAME = "data_config.ini";
private $_dbConn;
private $_config;
function __construct()
{
$this->_loadConfig();
$this->_dbConn = oci_connect($this->_config['db_usrnm'],
$this->_config['db_pwd'],
$this->_config['hostnm_sid']);
}
private function _loadConfig()
{
// Loads config
$path = dirname(__FILE__) . '/' . self::CONFIG_FILENAME;
$this->_config = parse_ini_file($path) ;
}
public function fetchLogs() {
$userid =$_POST["userid"];
$sql = "SELECT REQUEST_TIME,WORKFLOW_NAME,EVENT_MESSAGE
FROM AUTH_LOGS WHERE USERID = '".$userid."'";
//Preparing an Oracle statement for execution
$statement = oci_parse($this->_dbConn, $sql);
//Executing statement
oci_execute($statement);
$json_array = array();
while (($row = oci_fetch_row($statement)) != false) {
$rows[] = $row;
$json_array[] = $row;
}
echo json_encode($json_array);
}
}
$logAgent = new logAgent();
$logAgent->fetchLogs();
?>
I am doing this using asynchronous post method my defining a javascript file(script.js)
$(document).ready(function(){
$("#mybtn").click(function(e){
e.preventDefault();
var userid = $("#userid").val();
//$.post("index2.php", {"userid" : userid})
var posting = $.post( 'index2.php', {"userid" : userid});
posting.done(function( res ) {
var response = $.parseJSON(res);
$('#rawResponse').text(response);
});
});
})
I have many data for one user. And output display looks like:
03-SEP-18,softOtpCheck,OTP check passed,03-SEP-18,createAuthenticatedSession,yoya session Created.,03-SEP-18,createAuthenticatedSession,yoya session Created.,03-SEP-18,oamAuth,OAM context cookie collected.,03-SEP-18,softOtpCheck,OTP check passed,03-SEP-18,createAuthenticatedSession,yoya session Created.,03-SEP-18,createAuthenticatedSession,yoya session Created.,03-SEP-18,oamAuth,OAM context cookie collected.
But i want it as :
03-SEP-18,softOtpCheck,OTP check passed,
03-SEP-18,createAuthenticatedSession,yoya session Created.,
03-SEP-18,createAuthenticatedSession,yoya session Created.,
03-SEP-18,oamAuth,OAM context cookie collected.,
03-SEP-18,softOtpCheck,OTP check passed,
03-SEP-18,createAuthenticatedSession,yoya session Created.,
03-SEP-18,createAuthenticatedSession,yoya session Created.,
03-SEP-18,oamAuth,OAM context cookie collected.
How can i display my output in a newline?
I believe you want to change
$('#rawResponse').text(response);
to
$('#rawResponse').html('<pre>' + JSON.stringify(response, null, 2) + '</pre>);
See JSON.stringify and the enclosing pre tags will display the return value nicely.
Alternatively you could also put it into a textarea, it will also display the newlines properly.
If you want to echo the json data, you can returns prettified data with newline characters using JSON_PRETTY_PRINT
echo json_encode($json_array, JSON_PRETTY_PRINT);
Im trying to access session throw different controllers OR in different functions in one controller but when i try access the value from different function , variable is NULL
i read some documents (including cakephp session cookbook) and more , but i couldnt understand a bit on how to configure the session before using it.
i have a problem in one controller that im trying to use a session but the value is null after im writing it in another function!?
my other question is how can i avoid writing $this->request->session(); in every function that i want to use session.
CODE :
<?php
namespace App\Controller;
use App\Controller\AppController;
use App\Model\Entity\Answer;
use Cake\ORM\TableRegistry;
class ComlibsController extends AppController {
public function index() {
}
public function getResult(){
$this->viewBuilder()->layout('comlib'); //change the layout from default
$live_req = $this->request->data['searchBox']; // get the question
$session->write('comlib/question' , $live_req);
$query = $this->Comlibs->LFA($live_req); // get the first answer
$shown_answerID = array($query[0]['answers'][0]['id'], '2');
$this->Session->write(['avoidedID' => $shown_answerID]); //avoid the answer that user saw to repeat agian
$this->set('question',$query[0]['question']); // does work
//get the answers result
//and send the array to the
$fields = array('id','answer','rate' , 'view' , 'helpful');
for ($i = 0 ; $i <= 6 ; $i++) {
$this->set('id'.$i,$query[0]['answers'][$i][$fields[0]]);
$this->set('answer'.$i,$query[0]['answers'][$i][$fields[1]]);
$this->set('rate'.$i,$query[0]['answers'][$i][$fields[2]]);
$this->set('view'.$i,$query[0]['answers'][$i][$fields[3]]);
$this->set('helpful'.$i,$query[0]['answers'][$i][$fields[4]]);
}
}
public function moveon() {
$this->render('getResult');
$this->viewBuilder()->layout('comlib');
echo $question = $session->read('comlib/question'); // empty value echo
$avoidedIDs = $session->read('avoidedID');
var_dump($avoidedIDs); // returns NULL WHY ?
$theid = $this->request->here;
$query = $this->Comlibs->LFM($theid,$avoidedIDs,$question);
echo 'imcoming';
}
}
Thanks In Adnvanced
You use these codes for write and read session data:
$this->request->session()->write($name, $value);
$this->request->session()->read($name);
Please read this section in CakePHP book.
Try
$this->session()->write('avoidedID', $shown_answerID);
instead of
$this->session()->write(['avoidedID' => $shown_answerID]);
And try
$avoidedIDs = $this->session()->read('avoidedID');
instead of
$avoidedIDs = $session->read('avoidedID');
I Am trying to insert data in DB,But somehow NULL is inserted in DB
Here Is My Controller
foreach($this->input->post('resume_id') as $key =>$value ){
$ResumeInsert[$key]['resume_keyid'] = $Resume['resume_id'][$key];
$ResumeInsert[$key]['employer_name'] = $Resume['employer_name'][$key];
$ResumeInsert[$key]['start_Date'] = $Resume['start_Date'][$key];
$ResumeInsert[$key]['end_date'] = $Resume['end_date'][$key];
$ResumeInsert[$key]['type_id'] = $Resume['type_id'][$key];
$ResumeInsert[$key]['position'] = $Resume['position'][$key];
$ResumeInsert[$key]['responsibility'] = $Resume['responsibility'][$key];
$ResumeInsert[$key]['Skills'] = $Resume['Skills'][$key];
if(isset($Resume['id'][$key]) ){
$Key_Resume__ExistIDs[]=$Resume['id'][$key];
$ResumeUpdate[$key]=$ResumeInsert[$key];
$ResumeUpdate[$key]['resume_id']=$Resume['id'][$key];
unset($ResumeInsert[$key]);
}
else{
$ResumeInsert[$key]['resume_id'] = $GetLastID;
print_r ($ResumeInsert[$key]);exit;
$GetLastID++;
}
}
$idsToDelete='';
if(empty($ResumeInsert) && empty($ResumeUpdate)){
$idsToDelete=array_diff($Key_Resume_IDs,$Key_Resume__ExistIDs);
}
$status=$this->Resume_model->ProcessData($idsToDelete,$ResumeUpdate,$user_id,$ResumeInsert,$imgInsert,$imgUpdate);
redirect('Resume','refresh');
Here Is My Code Of Model
function ProcessData($idsToDelete,$tbl_resumeUpdate,$user_id,$tbl_resumeInsert,$imgInsert,$imgUpdate){
$this->db->trans_start();
if(!empty($idsToDelete)){
$this->delete_tbl_resume($idsToDelete);
}
if(!empty($tbl_resumeUpdate)){
//echo "up";exit;
$this->update_tbl_resume($tbl_resumeUpdate);
}
if(!empty($tbl_resumeInsert)){
//echo "int";exit;
$this->insert_tbl_resume($user_id,$tbl_resumeInsert);
}
if(!empty($imgInsert)){
$this->insert_tbl_file_paths($imgInsert);
}
if(!empty($imgUpdate)){
$this->update_tbl_file_paths($imgUpdate);
}
return $this->db->trans_complete();
}
This is Insert Query
function insert_tbl_resume($id,$arrtbl_resume){
$this->db->insert_batch('tbl_resume', $arrtbl_resume);
}
In Above Code,Null Value inserted In DB.
when i Print above query,it displays blank
Any Help Please?
You should use form_validation library. I'm giving you an example, you can edit and use it.
In autoload.php, edit $autoload['libraries'] = array(); line to:
$autoload['libraries'] = array('form_validation');
Then, use form_validation in your controller file. For example:
$this->form_validation->set_rules('resume_keyid', 'Resume ID', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->index() // if there is an error, user will redirect to this function
}
else
{
$this->Resume_model->ProcessData();
}
Also please use $this->input->post('resume_keyid', TRUE); structure in your model. "TRUE" means "open XSS filter". Because in CI 3, it comes off as default. If you don't want it, just remove. If you use CI 2, you don't need to add "TRUE".
A few suggestions:
1 - Don't use camelization when you name functions. For example; use process_data() instead of processData()
2 - Check CI Form Validation Document for all details (E.g. all references)
3 - I think you can use $this->db->insert();, just create an array and POST it. If you make it, you'll understand what's wrong.
I am trying to submit a EDIT form which edits Users Academics Details,
These Details have unique id in DB and my Code in Short Looks like below :
class edit extends ci_controller
{
function user_academics($id = NULL)
{
if(isset($id) == FALSE) //if link is ./edit/user_academics
{
$id = NULL;
$link = site_url('profile');
show_error("Invalid Page Request! <a href='$link' Go to Profile </a>");
}
$user_id = $this->session->userdata('user_id');
$data['fill'] = $this->edit_model->get_user_academics($id);
if($user_id != $data['fill']['user_id']) // check if logged in user is accessing his record or others
{
$link = site_url('profile');
show_error("This is an Invalid Request ! <a href='$link'>Go to Profile </a>");
}
else // actual work starts here
{
$this->session->set_flashdata('ua_id',$id); // update_academics will get this data
$this->load->view('edit/edit_3_view',$data);
}
}
function update_academics()
{
$ua_id = $this->session->flashdata('ua_id'); // flash data used here .
if( !$ua_id )
{
show_error('Sorry, This request is not valid!');
}
$academics = array(
// All post values
);
$this->edit_model->update_user_academics($academics,$ua_id);
//print_r($academics);
redirect('profile');
}
}
Now the problem is
- If I open two different records to edit, then It will set only one Session Flash value.
- And No matter what I edit , the existing values of the last flash value gets updated.
Please Suggest me another way or Correct me if I am wrong in above code . Thanks
save that flashdata in array, like:
$myArr = array('value 1', 'value 1');
//set it
$this->session->set_flashdata('some_name', $myArr);
And in view:
$dataArrs = $this->session->flashdata('some_name');
//loop thru $dataArrs to show the flashdata
Flash data is simply like variable which is available only in next request, you can bypass this behavior by using two different keys with record id in it, so that when you use flash data for showing message you can access key with particular record id.