My code is :
public function join_membership()
{
$this->layout = 'colorbox';
$membership_id = $this->Cookie->read('membership_id');
$membership = $this->Membership->find('first', array('conditions'=>array('Membership.id'=>$membership_id)));
$this->set('membership',$membership);
if($this->request->is('post'))
{
if($this->JoinMembership->save($this->request->data['JoinMembership']))
{
$this->redirect(array('action' => 'member_login'));
}
}
}
This code save the data in database properly but after that it displays blank page, it doesn't redirect to the given function.
Thanks in advance....
In case anybody has trouble telling where their whitespace/output is (like I did), put this small block right before your $this->redirect call:
$file = '';
$line = '';
if (headers_sent($file, $line)) {
die('Output in ' . $file . ' at line ' . $line);
}
It will stop your controller action and print out the exact file and line where the whitespace/output is.
Try with the following code into your if condition.
$this->redirect(array('controller' => 'Controller_Name', 'action' => 'member_login'));
You can also try to print something into if condition you used. Also use the else part and also print something into else part. Check it in debug mode 2.
1) Is the member_login action located in the same controller as join_membership? If no then add the Controller => "Some_Controller" key value paire to the array.
2) If one does not work, check if the if condition is working like so
if($this->JoinMembership->save($this->request->data['JoinMembership']))
{
debug("in");exit();
$this->redirect(array('action' => 'member_login'));
}
}
You should see "in" message if the if condition is returning true.
Please note that you can use
$this->redirect("action_name");
$this->redirect("/controller_name/action_name");
Related
Hi everyone I am getting the following error when I submit my form for my CI 3 website:
Fatal error: Call to a member function insert() on null
This error is occurring on line 20 which is:
$query = $this->db->insert('temp_subscribed_users', $data);
Here is the full function:
public function add_temp_user($key)
{
echo "hello";
$data = array(
'TEMP_EMAIL' => $this->input->post('email'),
'TEMP_KEY' => $key
);
echo var_dump($data);
$query = $this->db->insert('temp_subscribed_users', $data);
if($query)
{
return true;
}else{
return false;
}
}
I am not sure what it means by null. The table name is correct and I did a var_dump to confirm that the array is being populated. I also made sure that I am getting into the function by echoing "hello" and it is outputting onto the page.
Any help is appreciated thank you!
Additional info: Running using XAMPP localhost.
load database and then call insert function. Codeigniter does not load database automatically for the performance issue.
$this->load->database();
$query = $this->db->insert('temp_subscribed_users', $data);
Well first of all you're not utilizing the MVC model of codeigniter. Controller is for functions, Model is for the database connections.
First autoload your database, If not just put it in the code. But here is how it should look like.
CONTROLLER FUNCTION
public function add_temp_user($key)
{
echo "hello";
$this->load->model('MY_MODEL');
//If you're not autoloading db include the next line
//$this->load->library('database');
$data = array(
'TEMP_EMAIL' => $this->input->post('email'),
'TEMP_KEY' => $key
);
echo var_dump($data);
//If you confirmed the data var dumped
$success = $this->MY_MODEL->insert_to_db($data);
if($success == true)
{
//Do something
}
else
{
//Do something
}
}
MODEL
public function insert_to_db($data)
{
$query = $this->db->insert('temp_subscribed_users', $data);
//
if($query)
{
return true;
}
else
{
return false;
}
}
Make sure the TEMP_EMAIL and TEMP_KEY are the columns in your database and temp_subscribed_users is your table name
Try to solve your problem by getting into the autoload.php in the config folder and add database on the array for libraries, like this: $autoload['libraries'] = array('database');
Please check whether object is created or not.
Check that object is available in that class
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.
How can I detect if the user is on the homepage of my website with CakePhp?
May I use $this->webroot?
The goal is to do something only if the current page is the homepage.
Simply you can try this:
if ($this->request->here == '/') {
// some code
}
Also it is good to read this part of documentation:
You can use CakeRequest to introspect a variety of things about the
request. Beyond the detectors, you can also find out other information
from various properties and methods.
$this->request->webroot contains the webroot directory.
$this->request->base contains the base path.
$this->request->here contains the full address to the current request
$this->request->query contains the query string parameters.
You can find it by comparing the present page with webroot or base
if ($this->here == $this->webroot){ // this is home page }
OR
if ($this->here == $this->base.'/'){ // this is home page }
You can get it properly by checking against params like below:
if($this->params['controller']=='homes' && $this->params['action']=='index')
in this way you can check for any page of cakephp on view side
Assuming you are going to do something from the AppController, it's best to see if the current controller/action pair is the one you define as "homepage" (as Cake can route a user anywhere from the '/' route and you probably still want the logic to be triggered when the action is called directly with the full /controller/action URI and not just on /). In your AppController just add a check:
if ($this->name == 'Foo' && $this->action == 'bar') {
// Do your stuff here, like
echo 'Welcome home!';
}
That way it will trigger whenever the bar action is requested from the FooController. You can obviously also put this logic in the specific controller action itself (and that might make more sense since it's less overhead).
You can use $this->request->query['page'] to determine where you are,
if ( $this->request->query['page'] == '/' ){
//do something
}
Edit:
check $this->request object using echo debug($this->request), it contains many informations you can use. Here is a sample of what you get:
object(CakeRequest) {
params => array(
'plugin' => null,
'controller' => 'pages',
'action' => 'display',
'named' => array(),
'pass' => array(
(int) 0 => 'home'
)
)
data => array()
query => array()
url => false
base => ''
webroot => '/'
here => '/'
}
If your home page is home.ctp as mentionned by the cakePHP convention. In PagesController, you can change the display function to look like :
(added code starts at the comment /* Custom code start*/ )
public function display()
{
$path = func_get_args();
$count = count($path);
if (!$count) {
return $this->redirect('/');
}
$page = $subpage = null;
if (!empty($path[0])) {
$page = $path[0];
}
if (!empty($path[1])) {
$subpage = $path[1];
}
/* Custom code start*/
if("home"==$page){
// your code here
}
/* Custom code end*/
$this->set(compact('page', 'subpage'));
try {
$this->render(implode('/', $path));
} catch (MissingTemplateException $e) {
if (Configure::read('debug')) {
throw $e;
}
throw new NotFoundException();
}
}
The way I achieved that was by using $this->params. If you use print_r($this->params);, you will see the content of that variable for you. It will return an array. You will see the difference of when you are versus when you are not in the home page. You will have to use one of the keys in $this->params to make your evaluations with an if statement. That was how I achieved it. Maybe you can find this approach useful too.
I need little Active record help. I am trying to update page views which i store in database. Each time post() function runs, add +1 . Here is my code:
public function post($id) {
if($id == NULL){
redirect('blog');
}
else{
$this->db->where('entry_id',$id);
$this->db->set('views','views+1');
$this->db->update('entry');
Please help!
Correct your code like this for example:
public function post($id) {
if(!isset($id) || (int) $id<=0){
header('Location: /blog');
}
else{
$this->db->where('entry_id',$id);
$this->db->set('views','views+1');
$this->db->update('entry');
}
Mark the header('Location: /blog') - you should put here your real server path to the blog.
If you use a custom redirection function, like your redirect() then check if the is an output before calling her. Header redirection only works if no other output is sent to the browser before invoking it.
public function post($id) {
if($id == NULL){
redirect('blog');
}
else{
$this->db->where('entry_id',$id);
$this->db->set('views','views+1',FALSE);
$this->db->update('entry');
FALSE turns off Active record escaping,by default it ignores +1.
Hi there I have written a code that ietrates through whole array and copies the images to a folder and inserts data in record. Now funny thing is that $model->save()does not show error it returns true. and program never goes into else
now what happens loop continues to run and completes its ietration without breaking. I can not guess who is wrong. greater chances are me as i am most of time :)
here is code
protected function saveImage($formData,$model)
{
if ($formData === null)
return;
$idx=0;
foreach($formData['title'] as $image)
{
$model->title = $image;
$file= dirname(Yii::app()->request->scriptFile) . DIRECTORY_SEPARATOR
. DIRECTORY_SEPARATOR .'images\hotelImages'. DIRECTORY_SEPARATOR
. $model->hotel->name;
$model->image = Yii::app()->baseUrl. "/images/hotelImages/".$_FILES['HotelImages']['name'][$idx];//image path
if($model->save())
{
echo $idx.'<br /> it was sucess<br />';
If(file_exists($file))
{
copy($_FILES['HotelImages']['tmp_name'][$idx],$file."/".$_FILES['HotelImages']['name'][$idx]);
}
else
{
mkdir($file);
copy($_FILES['HotelImages']['tmp_name'][$idx],$file."/".$_FILES['HotelImages']['name'][$idx]);
}
$idx++;
}//if there was error
else
{
print_r($model->getErrors());
yii::app()->end();
return FALSE;
}
echo '<br />end reached <br />';
}
yii::app()->end();
return true;
}
var_dump for $formdata is
array
(
'title' => array
(
'0' => 'title1'
'1' => 'title2'
)
)
No mater what ever the ietration count for foreach loop database gets only single row
The save() method inserts a record into the database if it doesn't exist yet, and otherwise updates that same database record.
$model is being passed in as a method parameter, and I'm just assuming here that its title attribute is not the primary key.
In other words, you keep updating the same database record over and over, which is why you only see one record in the database.
#fivedigit's analysis is correct. My suggested fix would be to reduce the complexity of this method. Put everything inside the foreach in its own method (e.g. saveImage), then do something like:
foreach($formData['title'] as $image) {
$this->saveImage($image, new Image);
}
This method is a bit of a super-method, and you might find it easier to break it out into different methods. Perhaps use a component to handle the file copying, instead of filling up the controller.
And once again I am wrong :)
Issue was that in each foreach ietration the $model was previous and New instant of $model was not created and yii thought that hey its old one probably this Geek is updating it. so that is it.it updates in database.
just did
$model = new HotelImages;
before populating them
I thank fivedigit for Just an idea.
I have a strong believe on this
Most people says Little knowledge is dangerous...well that is true for
all except for programmers. Programmers are rare species and what it all takes is
a little idea/hint to do the thing
Yii CActiveRecord has a variable isNewRecord, its value is true when an object is created and remains true until a find or save function is not called. When a model calls save function, isNewRecord set to false.
So in your case you need to set this variable "isNewRecord" true each time before save function called or create a new model each time than call the save function.
See the changes in your code::
$model->setIsNewRecord(True); // changes code line
protected function saveImage($formData,$model)
{
if ($formData === null)
return;
$idx=0;
foreach($formData['title'] as $image)
{
$model->setIsNewRecord(True); // for each new record
$model->title = $image;
$file= dirname(Yii::app()->request->scriptFile) . DIRECTORY_SEPARATOR
. DIRECTORY_SEPARATOR .'images\hotelImages'. DIRECTORY_SEPARATOR
. $model->hotel->name;
$model->image = Yii::app()->baseUrl. "/images/hotelImages/".$_FILES['HotelImages']['name'][$idx];//image path
if($model->save())
{
echo $idx.'<br /> it was sucess<br />';
If(file_exists($file))
{
copy($_FILES['HotelImages']['tmp_name'][$idx],$file."/".$_FILES['HotelImages']['name'][$idx]);
}
else
{
mkdir($file);
copy($_FILES['HotelImages']['tmp_name'][$idx],$file."/".$_FILES['HotelImages']['name'][$idx]);
}
$idx++;
}//if there was error
else
{
print_r($model->getErrors());
yii::app()->end();
return FALSE;
}
echo '<br />end reached <br />';
}
yii::app()->end();
return true;
}