I have a problem using codeigniter, now I have a system that show you a question in a page called start, the question comes random from the database using this code.
$data['question'] = $this->Setting->Loop('challenges_questions', 'ORDER BY RAND() LIMIT 1');
then check the form_validation
if($this->form_validation->run() === TRUE){
foreach($data['question']->result() as $ques){
$query = $this->Challenges_Model->addAnswer($ques->the_answer);
}
}
this is the model
public function addAnswer($answer){
if($this->input->post('answer') == $answer){
if(!$this->session->userdata('is_stopped')){
$this->db->query("UPDATE challenges_scores SET points = points+1 WHERE user_id = ".$this->session->userdata('id').";");
//$this->db->set('points' , 'points+1');
//$this->db->where('user_id', $this->session->userdata('id'));
//$this->db->update('challenges_scores');
}else{
// unSet
$this->session->unset_userdata('is_stopped');
}
return TRUE;
}else{
return FALSE;
}
}
now my problem is when the user post the input (the answer), the query is refreshed, then the answer is changed then the form input answer is wrong.
is there any way to save data to use it after the post ?
The logic is the same as an update form:
Model:
function get() {
return $this->db->get('sometable')->result();
}
Controller:
function index() {
$data['result'] = $this->sommodel->get();
$this->load->view('someview', $data);
}
Here we get the post value if there is any (in case of bad form validation submit) and if not we have the value from the db
<input name="somefield" value="<?php isset($_POST['somefield']) { echo $_POST['somefield'] } else { echo $result->somefield; } ?>">
If it's just one thing just store it in a session variable and do the same logic by instead of $result->somefield you put $this->session->somefield. I wouldn't recommend this approach if it's alot of data.
Related
So I've built a small conditional to evaluate which button is pressed in my form (as there are 2). This works fine and fires off the correct method and writes the appropriate data to the DB, however my redirect is not working. It saves() to the DB and then simply stays on the page designated as the POST route.
I suspect the problem has something to do with my conditional and the use of $this.
Here is my check_submit method:
public function check_submit()
{
if(!is_null(Input::get('add_to_invoice'))){
$this->invoice_add_item();
} elseif(!is_null(Input::get('complete_invoice'))) {
$this->invoice_complete();
}
}
Here is one of the 2 methods which I am currently testing:
public function invoice_add_item()
{
$input = Request::all();
$invoice_items = new Expense;
$invoice_items->item_id = $input['item_id'];
$invoice_items->category_id = $input['category'];
$invoice_items->price = $input['price'];
$invoice_items->store_id = $input['store'];
if(Input::has('business_expense'))
{
$invoice_items->business_expense = 1;
}
else{
$invoice_items->business_expense = 0;
}
$invoice_items->save();
return redirect('/');
}
Perhaps there is a better way of handling this in my routes(web) file, but I'm not sure how to go about this.
You should add the return to the check_submit() method. Something like
public function check_submit()
{
if(!is_null(Input::get('add_to_invoice'))){
return $this->invoice_add_item();
} elseif(!is_null(Input::get('complete_invoice'))) {
return $this->invoice_complete();
}
}
Better yet, you should probably return a boolean on invoice_add_item() and based on that, redirect the user to the correct place (or with some session flash variable with an error message)
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.
I'm trying to delete multiple private messages from my database by selecting multiple checkboxes in the inbox and clicking submit to delete. I have the code below but nothing happens. I'm not sure what I'm missing..
View:
<?php echo form_open('pm/remove_checked'); ?>
<?php foreach ($query as $row): ?>
<input type="checkbox" name="msg[]" value="<?php echo $row->id; ?>" />
<?php echo $row->from; ?>
<?php echo $row->subject; ?>
<?php echo date("m/d/Y",strtotime($row->msg_date)); ?>
<?php endforeach; ?>
<?php echo form_submit('delete', 'Delete'); ?>
</form>
Controller:
function remove_checked()
{
//validation rules
$this->form_validation->set_rules('msg[]', 'Private Message', 'required|xss_clean');
if ($this->form_validation->run() == FALSE)
{
$data['query'] = $this->Pm_model->received_msg();
$this->load->view('pm/inbox', $data);
}
else //success
{
$checked_messages = $this->input->post('msg'); //selected messages
$this->Pm_model->delete_checked($checked_messages);
//redirect to inbox
}
}
Model:
function delete_checked($checked_messages)
{
$checked_messages = array();
foreach ($checked_messages as $msg_id):
$this->db->select('id');
$this->db->from('user_msg');
$this->db->where('id', $msg_id);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() > 0) //if message exists
{
$this->db->where('id', $msg_id);
$this->db->where('recipient', $this->users->get_user_id()); //verify if recipient id is equal to logged in user id
$this->db->delete('user_msg');
}
else
{
return FALSE;
}
endforeach;
}
In your current delete_checked() method, you are returning FALSE as soon as the first message is "found" that doesn't exist, this will prevent the rest of the messages from being deleted as return will stop execution of the loop. If you want to do it this way, use continue instead and consider using transactions.
If you don't particularly care about generating individual errors for each message, your model function can be simplified a bit:
function delete_checked($message_ids)
{
$this->db
->where_in('id', $message_ids)
->where('recipient', $this->users->get_user_id())
->delete('user_msg');
return $this->db->affected_rows() > 0;
}
This will just attempt to delete the records. If they don't exist they will be ignored, and $this->db->affected_rows() should return the number of messages deleted. You can compare it to count($message_ids) if you want to ensure that all messages selected were deleted, or use this example method that only checks if at least one message was deleted. If the message doesn't exist, you don't need to delete it anyways.
All the stuff Chris Schmitz mentioned is correct and important as well, you have some very basic errors. You may want to cast to array instead of assigning $checked_messages to an empty array if you expect you may be passing a single id (integer or string) to this function. Like this:
$message_ids = (array) $message_ids;
You are assigning $checked_msg to the inputs that are checked, but then you are passing a different variable called $checked_messages to the model. You'll want to pass the $checked_msg var to the model.
Also, in your model, you are redeclaring the $checked_messages var and setting it to an empty array. You'll need to remove that otherwise it will overwrite the info you are passing to the method.
I created a helper for returning a user's username if the user's unique id is known.
if ( ! function_exists('get_username'))
{
function get_username($user_id)
{
$ci=& get_instance();
$ci->load->database();
if (empty($user_id))
{
return FALSE;
}
$ci->db->select('username');
$ci->db->where('id', $user_id);
$ci->db->where('activated', 1);
$ci->db->where('banned', 0);
$ci->db->limit(1);
$query = $ci->db->get('users');
if ($query->num_rows() > 0) //if user exists
{
$row = $query->row();
return $row->username;
}
else
{
return FALSE;
}
}
}
This works in my view if for instance I try:
echo get_username($this->uri->segment(3)); //uri segment 3 is a user id.
However want to send the username to my view via controller. I tried the following in my controller:
function write_message($user_id = '') //function parameter is 3rd uri segment
{
$data['username'] = get_username($user_id);
$this->load->view('my_view', $data);
}
Then in my view I have
echo $username which echoes array instead of the username. What am I doing wrong here?
Your criteria should be clear, and the usrname should be unique i think, so...
if ($query->num_rows() == 1) //if user exists, and unique
{
$res = $query->result_array();
return $res[0]['username'];
}
else
{
return FALSE;
}
Upon using <pre>print_r($username)</pre> in my view (as suggested by Alfonso) it was easy to spot the issue, being an identical variable name in my view which was another array. Correct answer goes to anyone that gives a good suggestion/input for my helper or Alfonso if he submits his post as answer.