When I access the wrong function in my controller, a 404 error page is working well. But, when i access url like 'http://example.com/model/detail/116', which 116 is wrong number [are not in the database], my 404 error page not working.
I have this code in my controller:
public function detail()
{
$id['id_galeri'] = $this->uri->segment(3);
$detail = $this->app_model->getSelectedData("tbl_galeri",$id);
foreach($detail->result() as $d)
{
$bc['jdl'] = "View";
$bc['id_galeri'] = $d->id_galeri;
$bc['nama'] = $d->nama;
$bc['foto'] = $d->foto;
$bc['deskripsi'] = $d->deskripsi;
$bc['stts_input'] = "deskripsi";
}
if($this->uri->segment(3) == '' && $id['id_galeri'] == FALSE)
{
$segment_url = 0;
}else{
if(!is_numeric($this->uri->segment(3)) || !is_string($this->uri->segment(3))){
redirect('404');
}else{
$segment_url = $this->uri->segment(3);
}
}
$this->load->view('frontend/global/bg_top');
$this->load->view('frontend/page/bg_view_model',$bc);
$this->load->view('frontend/global/bg_footer');
}
Sorry for my bad english, please help :-)
Thank you..
Instead of:
redirect('404');
try using CodeIgniter's native:
show_404('page');
EDIT
Try this code, a bit cleaned up and the checks are done before they're saved for views use.
public function detail()
{
$id['id_galeri'] = $this->uri->segment(3);
// Check if the supplied ID is numeric in the first place
if ( ! is_numeric($id['id_galeri']))
{
show_404($this->uri->uri_string());
}
// Get the data
$detail = $this->app_model->getSelectedData("tbl_galeri",$id);
// Check if any records returned
if (count($detail->result()) === 0)
{
show_404($this->uri->uri_string());
}
foreach($detail->result() as $d)
{
$bc['jdl'] = "View";
$bc['id_galeri'] = $d->id_galeri;
$bc['nama'] = $d->nama;
$bc['foto'] = $d->foto;
$bc['deskripsi'] = $d->deskripsi;
$bc['stts_input'] = "deskripsi";
}
/**
* Here do whatever you want with the $segment_url which doesn't seem to be
* used in your code
*/
$this->load->view('frontend/global/bg_top');
$this->load->view('frontend/page/bg_view_model',$bc);
$this->load->view('frontend/global/bg_footer');
}
Related
This has been giving a
404 page error not found
and i don't know why.
public static function getGeneration($currentParent, $rootParent){
// dd($rootParent);
$user = User::where("username", $currentParent)->first();
$generation =[];
$x = 0;
$bool = true;
while ($bool) {
if($x==0){
$generation[$x] = (User::where("username", $user->sponsor_username)
->firstOrfail())
->sponsor_username;
}else{
$generation[$x] = (User::where("username", $generation[$x-1])
->firstOrfail())
->sponsor_username;
}
if( $x > 0 ){
if($news = $generation[$x] == $rootParent){
dd($news);
$bool = false;
}
}
$x++;
}
return $generation;
}
what this method basicaly does is go through a database and find out who brought a particular user into a system, because is user has a sponsor_username against it on the database, the last if statement is meant to stop when it discovers that it has reached the root user.
I am trying to get a request from the input I just got where if the request input recommendation is No or KIV, it will redirect to home if not it will redirect to another page. But the problem now is that if the recommendation I put is Yes and some other things as No, it will redirect me to home instead of another page. Can someone help me out? Thanks a lot
public function eval(Request $request){
$Evaluation = new evaluation;
$personal_info = new personal_info;
$Evaluation->recommendation = $request->input('recommendation');
$Evaluation->training_schedule = $request->input('training_schedule');
$Evaluation->training_date = $request->input('training_date');
$Evaluation->PortalLogin = $request->input('PortalLogin');
$id = $request->user_id;
$id= personal_info::find($id);
$id->evaluations()->save($Evaluation);
if(($Evaluation->recommendation = $request->input('recommendation')) == 'No' || 'KIV')
return redirect('/home');
else{
return redirect(url('/user/showtest/'.$id->id.'/test) );
}
They syntax of your "if statement" is incorrect. || 'Kiv' this statement is evaluated alone and not against recommendation, so change the code to this way
$recommendation = $Evaluation->recommendation = $request->input('recommendation');
if( $recommendation == 'No' || $recommendation == 'KIV')
return redirect('/home');
else {
return redirect(url('/user/showtest/'.$id->id.'/test) );
}
I have codeigniter application which working well in justhost. I am trying to transfer it to bigrock host. But in new host its not working I can only see blank page with 500 error,no error logs in cpanel. Followed many solution in stackoverflow but couldn't fix(innitioally i thought its .htaccess problem), and now I tried define environment variable to development, I can see php error which says as below
A PHP Error was encountered
Severity: Compile Error
Message: Can't use method return value in write context
Filename: models/Home_model.php
Line Number: 77
Backtrace:
Home model screen shot
login function which is in home model:
public function login($data) {
if(filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
$res = $data['email'];
}
else {
$settings = get_setting();
$pre = $settings->id_prefix;
$res = trim($data['email'],$pre);
}
$this->db->select('*');
$this->db->from('users');
$this->db->join('profiles', 'profiles.email = users.email','left');
$this->db->where('user_status','1');
$this->db->where('users.email', $res);
$this->db->or_where('matrimony_id',$res);
$chk_qry = $this->db->get();
//$chk_qry = $query->row();
//echo $this->db->last_query();die;
if ($chk_qry->num_rows() == 1) {
$pass = $this->encrypt->decode($chk_qry->row()->password);
if($data['password'] == $pass) {
$this->db->where('user_id', $chk_qry->row()->user_id);
$usr_qry = $this->db->get('profiles');
if(!empty($usr_qry->result())) {
if($usr_qry->result()[0]->profile_status != 2) {
if($usr_qry->result()[0]->profile_status != 4) {
if($usr_qry->result()[0]->profile_approval == 1) {
$status = 1;
$this->session->set_userdata('logged_in',$usr_qry->result()[0]);
$data1['date_time'] = date('Y-m-d H:i:s', time());
//$data1['user_id']=$usr_qry->result()[0]->user_id;
$data1['matrimony_id']=$usr_qry->result()[0]->matrimony_id;
$query = $this->db->where('matrimony_id',$data1['matrimony_id']);
$query = $this->db->get('active_members');
if ($query->num_rows() > 0){
$this->db->where('matrimony_id',$data1['matrimony_id']);
$this->db->update('active_members',$data1);
} else {
$this->db->insert('active_members', $data1);
}
} else { $status = 2; } // Profile Not Approved
} else { $status = 7; } // Profile Deactivated
} else { $status = 5; } // Profile Deleted or Banned
} else { $status = 6; } // No Accounts Found
} else { $status = 3; } // Ivalid Password
} else { $status = 4; } // Email not exist
return $status;
}
I wonder how this same script working fine in justhost.
Solved problem!!! silly me,
Updated php version from 5.4 to 5.6
I have a strange problem with a function i wrote. When returning an hardcoded string like "Hello" it returns this value, but when i store this value in a variable it doesn't return anything.
Also when i don't store it in a variable and try to return it nothing gets returned.
Below is my code. Can anybody see what i'm doing wrong?
Thanks in advance.
public function getPath($pageID = null) {
if($pageID == null) $pageID = $this->id;
$data = $this->_db->fetch_array("SELECT * FROM `pages` WHERE `id` = '".$pageID."'");
if(!empty($data)) {
$this->tempPath[] = $data['basename'];
if($data['parentID'] != 0) {
$this->getPath($data['parentID']);
} else {
$returnPath = $this->tempPath;
$this->tempPath = array();
$returnPath = implode('/', array_reverse($returnPath));
//This variable holds the value, when echo'ed its the correct value
echo $returnPath;
return $returnPath;
}
}
}
Rewrote the code to the following and now it's working
public function getPath($pageID = null) {
if($pageID == null) $pageID = $this->id;
$data = $this->_db->fetch_array("SELECT * FROM `pages` WHERE `id` = '".$pageID."'");
if(!empty($data)) {
$this->tempPath[] = $data['basename'];
}
return implode('/', $this->tempPath);
}
Problem was that the code was in a foreach loop which kept overwriting the correct values and looping till there is no path to return. Thanks for the suggestions.
More code isn't always better :-)
I am working with SilverStripe, and I am working on making a newspage.
I use the DataObjectAsPage Module( http://www.ssbits.com/tutorials/2012/dataobject-as-pages-the-module/ ), I got it working when I use the admin to publish newsitems.
Now I want to use the DataObjectManager Module instead of the admin module to manage my news items. But this is where the problem exists. Everything works fine in draft mode, I can make a new newsitem and it shows up in draft. But when I want to publish a newsitem, it won't show up in the live or published mode.
I'm using the following tables:
-Dataobjectaspage table,
-Dataobjectaspage_live table,
-NewsArticle table,
-NewsArticle_Live table
The Articles have been inserted while publishing in the Dataobjectaspage table and in the NewsArticle table... But not in the _Live tables...
Seems the doPublish() function hasn't been used while 'Publishing'.
So I'm trying the use the following:
function onAfterWrite() {
parent::onAfterWrite();
DataObjectAsPage::doPublish();
}
But when I use this, it gets an error:
here is this picture
It seems to be in a loop....
I've got the NewsArticle.php file where I use this function:
function onAfterWrite() {
parent::onAfterWrite();
DataObjectAsPage::doPublish();
}
This function calls the DataObjectAsPage.php file and uses this code:
function doPublish() {
if (!$this->canPublish()) return false;
$original = Versioned::get_one_by_stage("DataObjectAsPage", "Live", "\"DataObjectAsPage\".\"ID\" = $this->ID");
if(!$original) $original = new DataObjectAsPage();
// Handle activities undertaken by decorators
$this->invokeWithExtensions('onBeforePublish', $original);
$this->Status = "Published";
//$this->PublishedByID = Member::currentUser()->ID;
$this->write();
$this->publish("Stage", "Live");
// Handle activities undertaken by decorators
$this->invokeWithExtensions('onAfterPublish', $original);
return true;
}
And then it goes to DataObject.php file and uses the write function ():
public function write($showDebug = false, $forceInsert = false, $forceWrite = false, $writeComponents = false) {
$firstWrite = false;
$this->brokenOnWrite = true;
$isNewRecord = false;
if(self::get_validation_enabled()) {
$valid = $this->validate();
if(!$valid->valid()) {
// Used by DODs to clean up after themselves, eg, Versioned
$this->extend('onAfterSkippedWrite');
throw new ValidationException($valid, "Validation error writing a $this->class object: " . $valid->message() . ". Object not written.", E_USER_WARNING);
return false;
}
}
$this->onBeforeWrite();
if($this->brokenOnWrite) {
user_error("$this->class has a broken onBeforeWrite() function. Make sure that you call parent::onBeforeWrite().", E_USER_ERROR);
}
// New record = everything has changed
if(($this->ID && is_numeric($this->ID)) && !$forceInsert) {
$dbCommand = 'update';
// Update the changed array with references to changed obj-fields
foreach($this->record as $k => $v) {
if(is_object($v) && method_exists($v, 'isChanged') && $v->isChanged()) {
$this->changed[$k] = true;
}
}
} else{
$dbCommand = 'insert';
$this->changed = array();
foreach($this->record as $k => $v) {
$this->changed[$k] = 2;
}
$firstWrite = true;
}
// No changes made
if($this->changed) {
foreach($this->getClassAncestry() as $ancestor) {
if(self::has_own_table($ancestor))
$ancestry[] = $ancestor;
}
// Look for some changes to make
if(!$forceInsert) unset($this->changed['ID']);
$hasChanges = false;
foreach($this->changed as $fieldName => $changed) {
if($changed) {
$hasChanges = true;
break;
}
}
if($hasChanges || $forceWrite || !$this->record['ID']) {
// New records have their insert into the base data table done first, so that they can pass the
// generated primary key on to the rest of the manipulation
$baseTable = $ancestry[0];
if((!isset($this->record['ID']) || !$this->record['ID']) && isset($ancestry[0])) {
DB::query("INSERT INTO \"{$baseTable}\" (\"Created\") VALUES (" . DB::getConn()->now() . ")");
$this->record['ID'] = DB::getGeneratedID($baseTable);
$this->changed['ID'] = 2;
$isNewRecord = true;
}
// Divvy up field saving into a number of database manipulations
$manipulation = array();
if(isset($ancestry) && is_array($ancestry)) {
foreach($ancestry as $idx => $class) {
$classSingleton = singleton($class);
foreach($this->record as $fieldName => $fieldValue) {
if(isset($this->changed[$fieldName]) && $this->changed[$fieldName] && $fieldType = $classSingleton->hasOwnTableDatabaseField($fieldName)) {
$fieldObj = $this->dbObject($fieldName);
if(!isset($manipulation[$class])) $manipulation[$class] = array();
// if database column doesn't correlate to a DBField instance...
if(!$fieldObj) {
$fieldObj = DBField::create('Varchar', $this->record[$fieldName], $fieldName);
}
// Both CompositeDBFields and regular fields need to be repopulated
$fieldObj->setValue($this->record[$fieldName], $this->record);
if($class != $baseTable || $fieldName!='ID')
$fieldObj->writeToManipulation($manipulation[$class]);
}
}
// Add the class name to the base object
if($idx == 0) {
$manipulation[$class]['fields']["LastEdited"] = "'".SS_Datetime::now()->Rfc2822()."'";
if($dbCommand == 'insert') {
$manipulation[$class]['fields']["Created"] = "'".SS_Datetime::now()->Rfc2822()."'";
//echo "<li>$this->class - " .get_class($this);
$manipulation[$class]['fields']["ClassName"] = "'$this->class'";
}
}
// In cases where there are no fields, this 'stub' will get picked up on
if(self::has_own_table($class)) {
$manipulation[$class]['command'] = $dbCommand;
$manipulation[$class]['id'] = $this->record['ID'];
} else {
unset($manipulation[$class]);
}
}
}
$this->extend('augmentWrite', $manipulation);
// New records have their insert into the base data table done first, so that they can pass the
// generated ID on to the rest of the manipulation
if(isset($isNewRecord) && $isNewRecord && isset($manipulation[$baseTable])) {
$manipulation[$baseTable]['command'] = 'update';
}
DB::manipulate($manipulation);
if(isset($isNewRecord) && $isNewRecord) {
DataObjectLog::addedObject($this);
} else {
DataObjectLog::changedObject($this);
}
$this->onAfterWrite();
$this->changed = null;
} elseif ( $showDebug ) {
echo "<b>Debug:</b> no changes for DataObject<br />";
// Used by DODs to clean up after themselves, eg, Versioned
$this->extend('onAfterSkippedWrite');
}
// Clears the cache for this object so get_one returns the correct object.
$this->flushCache();
if(!isset($this->record['Created'])) {
$this->record['Created'] = SS_Datetime::now()->Rfc2822();
}
$this->record['LastEdited'] = SS_Datetime::now()->Rfc2822();
} else {
// Used by DODs to clean up after themselves, eg, Versioned
$this->extend('onAfterSkippedWrite');
}
// Write ComponentSets as necessary
if($writeComponents) {
$this->writeComponents(true);
}
return $this->record['ID'];
}
Look at the $this->onAfterWrite();
It probably goes to my own function on NewsArticle.php and there starts the loop! I'm not sure though, so i could need some help!!
Does anyone knows how to use the doPublish() function?
The reason that is happening is that in the DataObjectAsPage::publish() method, it is calling ->write() - line 11 of your 3rd code sample.
So what happens is it calls ->write(), at the end of ->write() your onAfterWrite() method is called, which calls publish(), which calls write() again.
If you remove the onAfterWrite() function that you've added, it should work as expected.
The doPublish() method on DataObjectAsPage will take care of publishing from Stage to Live for you.