In this code below, $alb->error has an error message in it. I can verify this with echo, no problem.
The issue arises when I want to catch that error in an if clause. First, the code:
if($action == "add")
{
//PUT CODE TO SAVE A NEW ALBUM HERE
//SHOULD RETURN ALBUM ID
$alb = new album();
//fill object album with properties to be saved
$alb->date = checkNull($_POST['alb_date']);
$alb->name = checkNull($_POST['alb_name']);
$alb->desc = checkNull($_POST['alb_desc']);
$alb->cat_id = $_POST['categories'];
//call save method of album
$alb->create_album();
//catch error
if($alb->error <> "")
{
header("Location: add_album.php?error='$alb->error'");
}
//set album id to pass it along to add_pictures
$alb_id = $alb->id;
}
elseif($action == "edit")
{
//PUT CODE TO SAVE EDITED ALBUM HERE
//SHOULD RETURN ALBUM ID
}
header("Location: add_pictures.html?alb_id='$alb_id'");
After $alb->create_album(), $alb's error property is filled by omitting a required field in the input form. This is what I want. But then, I need to catch that error, and redirect the user to the previous page, where the error will be displayed.
Here's what I've tried so far:
//catch error
if(isset($alb->error))
{
header("Location: add_album.php?error='$alb->error'");
}
Didn't work.
//catch error
if(!is_null($alb->error))
{
header("Location: add_album.php?error='$alb->error'");
}
No cigar.
//catch error
if($alb->error <> "")
{
header("Location: add_album.php?error='$alb->error'");
}
still, zero joy.
The if clause never gets processed. What am I missing?
Thank you for your time.
So the problem was that I had a header redirect after my outer if clause for the type of action: if action=add or edit. When I wrapped it in an else clause, it worked:
}
elseif($action == "edit")
{
//PUT CODE TO SAVE EDITED ALBUM HERE
//SHOULD RETURN ALBUM ID
}
else
{
header("Location: add_pictures.html?alb_id='$alb_id'");
}
Thanks for your help!!
Related
Suppose I have written the following function to check empty posted values:
function checkEmpty($postValue, $msg){
if($postValue == null){
return alert_danger($msg);
exit(); // NOT WORKING AS EXPECTED
}
}
And I am trying to call it for several input values this way:
echo checkEmpty($city, "City cannot be empty");
echo checkEmpty($phone, "phone cannot be empty");
echo checkEmpty($name, "name cannot be empty");
Now when I call this function above it echoes all the three values as it should be but I do not want that. I want it to return 1 error at a time. If city is empty it should return City cannot be empty only and not the others. When the user has corrected the error it should then proceed to check the next error. But it seems that the exit() used inside the function is not working as expected. I could use the following method:
if($name == null){
echo alert_danger("Please enter your Name.");
exit();
}
if($email == null){
echo alert_danger("Please enter your Email ID.");
exit();
}
if($phone == null){
echo alert_danger("Please enter your Phone number.");
exit();
}
But that makes the code too big unnecessarily if I have 15-20 variables to be checked. That's why I wanted to use the function method here as tried earlier. What should be the solution?
Use a function that echoes the error then dies after:
function checkEmpty($postValue, $msg){
if($postValue == null){
echo alert_danger($msg);
exit();
}
}
checkEmpty($city, "City cannot be empty"); //without echo
I have a problem with updating database table in cakephp...
So I have a profile page where the logged in user can see and update his personal information. Here is my solution for it (yes I know it's not the best...)
if($this->request->is('post')) {
$data = $this->request->data['user-profile'];
// $uid = $this->Session->read("WebUser.id");
$uid = 1;
$user_data = $this->WebUser->find('first', array('conditions'=>array('id'=>$uid)));
$updated_fields = '';
foreach($data as $key => $value) {
if($key != 'state'){
if(empty($value)) {
$this->Session->setFlash("Please fill in all the required fields");
return;
}
}
if($user_data['WebUser'][$key] != $value) {
if($key == 'email') {
$mail_check = $this->WebUser->find('first', array('conditions'=>array('email'=>$value, 'id !='=>$uid)));
if($mail_check) {
$this->Session->setFlash("This e-mail is already registered");
return;
}
}
$updated_fields .= "'".$key."'=>'".$value."',";
}
}
if($updated_fields != '') {
$updated_fields .= "'modified'=>'".date("Y-m-d H:i:s")."'";
$this->WebUser->read(null, $uid);
$this->WebUser->set(array('first_name'=>'John','modified'=>'2014-12-30 10:53:00'));
if($this->WebUser->save()) {
$this->printr($this->data);
$this->WebUser->save();
$this->Session->setFlash("Success : Profile data is now modified", array("class"=>"success_msg"));
} else {
$this->Session->setFlash("Error : Data modifying isn't complete. Please try again!");
}
}
return;
}
So this code fetches the user info from the database and looks for those fields which are edited on profile page. Problem is when I want to save the data it give me back false and didn't save it... Does someone have a solution for this?
Try putting
$this->WebUser->validationErrors;
in else part and check whether there are any validation errors or not.
Like this:
if($this->WebUser->save()) {
$this->printr($this->data);
$this->WebUser->save();
$this->Session->setFlash("Success : Profile data is now modified", array("class"=>"success_msg"));
} else {
echo "<pre>";print_r($this->WebUser->validationErrors);die();
$this->Session->setFlash("Error : Data modifying isn't complete. Please try agin!");
}
Did you tried to set id directly?
$this->WebUser->id = $uid;
Also, CakePHP is automatically update modified field in your table after any transactions. So you don't have to set it directly (but you can if you want any other date value).
About validation. I recommend you to read about Data Validation in CakePHP, because that validation is not good, it's can be handled by models.
Also. You can get any validation errors from models using Model::$validationErrors.
debug($this->Recipe->validationErrors);
The problem with this code was that didn't wanted to save the posted data ( debug($this->WebUser->save) has give me back false). At the end I didn't found the solution why this code not worked but the conclusion is that you never need to use more users table than one. So now I have a Users and Groups tables, and different type of users are connected to their groups(Admin, User, ...).
I'm currently trying to develop the following function:
When someone wants to see their album or profile photos, I would like to use either album_id or id in the url, like this:
album.php?album_id=(numeric Number)
album.php?id=(numeric number)
I am currently able to execute the first command and when I attempt the second, it fails to load instead I'm taken to the index page (as per the script's design.)
Here is my code:
$album_id = addslashes(is_numeric($HTTP_GET_VARS["album_id"]));
$profile_id = addslashes(is_numeric($HTTP_GET_VARS["id"]));
?>
<?php
if($album_id==Null||!$profile_id==Null)
{
print("<script language='JavaScript'> window.location='index.php'; </script>");
}
else
{
if ($album_id==$album_id)
{
include("/home/emo/public_html/incldues/layout/photos/pages/albums/album_photos.php");
}
else
{
if ($profile_id==$profile_id)
{
include("/home/emo/public_html/incldues/layout/photos/pages/albums/profile_photos.php");
}
else
{
include("/home/emo/public_html/incldues/layout/photos/pages/albums/album_photos.php");
}
}
}
?>
And to clarify, those "pages" contain nothing but bold saying:
Show album photos and Show user photos
But what I can't seem to fathom as to what my problem might be.
If you call album.php?album_id={id}, $_GET['id'] is null, making your first if statement return to the index page.
if (($album_id == null) || ($profile_id == null)) { ... }
One will always be null unless you call album.php?album_id={aid}&id={pid}
if (($album_id == null) && ($profile_id == null)) {
# redirect to index.php
} else {
if ($album_id != null) {
# load album
} else if ($profile_id != null) {
# load profile
} else {
# both given, redirect to error.
}
}
Your condition if($album_id==$album_id) will always be true because they both are same and the else part is never executed.
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.
Im trying to test a pin number in the database compared to one entered by a user, whenever i run it i get a 'Trying to get property on non-object' error ... I cant seem to spot where im going wrong, could someone please help me out ... Its saying the error is on the $thepin = $pins->pin; line
The code i have in my controller is as follows:
function check_pin()
{
$pin = md5($this->input->post('oldpin'));
$email = $this->input->post('email');
$existingpin = $this->users->get_pin_by_email($email);
foreach($existingpin as $pins){
$thepin = $pins->pin;
}
if($pin != $thepin){
$this->form_validation->set_message('check_pin', 'The Old Pin Number does not match the existing one');
return FALSE;
} else {
return TRUE;
}
}
and the following is the code in my model
function get_pin_by_email($emailaddress)
{
$this->db->where('LOWER(email)=', strtolower($emailaddress));
$query = $this->db->get($this->table_name);
if ($query->num_rows() == 1) return $query->row();
return NULL;
}
The Controller code should be:-
function check_pin()
{
$pin = md5($this->input->post('oldpin'));
$email = $this->input->post('email');
$existingpin = $this->users->get_pin_by_email($email);
foreach($existingpin as $pins){
// Check for the NULL return
if ($pins != NULL && is_object($pins)) {
$thepin = $pins->pin;
}
}
if($pin != $thepin){
$this->form_validation->set_message('check_pin', 'The Old Pin Number does not match the existing one');
return FALSE;
} else {
return TRUE;
}
}
If you look closely in the model code, you will find that you are returning two data types - one is Object & another is NULL. So in your controller code, you should also check that accordingly.
Hope it helps.