Codeigniter delete multiple rows with checkboxes - php

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.

Related

How to display data from MYSQL in codeignitor?

I want to create a dynaic page, I have created model and controller and also data subitted in database successfully. Now, i'm having problem while displaying that data on front end.
Here is my Modal:
function getcorporate(){
$q="SELECT * from corporate";
$query=$this->db->query($q);
return $query->result_array();
}
Here is my Controller:
function corporate()
{
$popular['popular'] = $this->auth_model->getPopularcourses();
$data1['corporate'] = $this->auth_model->getcorporate();
$data["institute_details"] = $this->auth_model->getInstitutedetails();
$data1['course'] = $this->auth_model->getcoursesdetailes();
$this->load->view('nulearnFront/header', $data);
$this->load->view('nulearnFront/corporate', $data1);
$this->load->view('nulearnFront/footer', $popular);
}
Try this
First you can print_r() the data you receive.
print_r($corporate);
After that you can use foreach to display all the data
foreach($corporate as $value)
{
////do code according to your requirement
}
I hope this may be help out to solve your problem
Add View file this code
<?php
if (isset($corporate) && !empty($corporate)) {
foreach ($corporate as $cdata) {
echo $cdata->YourValue(db column name);
}
}
?>
You are so close to the answer. You are passing the data from your Controller class. So what you have to do is just get that data as the follows,
I get the corporate values as it is returning an array data. So here you go,
In your view.php file,
<?php
if (isset($corporate)) { // Check if the data is set or not
foreach ($corporate as $corporateData) {
?>
// Your HTML goes here, table or etc.
<?php echo $corporateData->databaseColumnName // Value that need to print from the database ?>
<?php
}
}
?>
Hope this helps you.
print the query and run it to check
function getcorporate(){
$q="SELECT * from corporate";
$query=$this->db->query($q);
print_r($this->db->last_query());die();
return $query->result_array();
}
if query works fine then you can foreah the query
foreach($corporate as $corporate)
{
echo corporate;
}
if it does not return result then change result_array() to result() in model

Why does CI create a new row instead of updating?

I'm creating a UI in my application which will allow the user to decide the state of received content, this includes updating it. How does CI handle this?
I've tried the different update methods provided in the query builder part of the documentation, including replace and update, I pass on the data from the view to the controller, to the model in the form of an array. Yet still, when I try it, it creates a new row with that single value and with all other columns empty.
view.php
<form action="Application/Update" method="get">
<input type="hidden" name="mar-id" value="<?php echo $row['id']; ?>">
<input type="hidden" name="mar-read" value="New-value">
<?php echo anchor('http://localhost/dir/dir/dir/index.php/Application/Update', 'update'); ?>
</form>
controller.php
public function Update() {
$this->load->helper('url');
$this->load->model('Main');
$id = $this->input->post('mar-id');
$value = $this->input->post('mar-read');
$mar = $this->Main->Update($id, $value);
if ($mar == TRUE) {
redirect('http://localhost/dir/dir/dir/index.php/Application/Otherpage', 'refresh');
}
else {
redirect('http://localhost/dir/dir/dir/index.php/Application/Otherpage');
}
}
model.php
public function Update($id, $value) {
$data = array(
'status' => $value
);
$this->db->where('id', $id);
$update = $this->db->update('table', $data);
}
As I said, I expect the row to be updated based on the row-id provided. Instead it creates a completely new row with that single value. It doesn't return any error messages though.
There are a number of mistakes here.
SO to date we have established that performing var_dumps in the controller results in NULL for all your "POST" values.
I've assumed the following for simplicity.
Controller Name is: Program.php (Application is NOT an Allowed controller name as it's a foldername)
Model Name is: Mdl_update.php
View is: update_view.php
Issue #1:
Your Form has an issue where you are using an anchor tag which is just a link. It does nothing in submitting any data from the form.
So we have to remove the Anchor Tag and replace it with a Form Submit. You have to Submit the form to get any chance of sending the form data.
For testing your GET and POST I've added in Two different Forms.
In update_view.php
<!-- Set the Method to GET -->
<form action="program/update" method="get">
<input type="hidden" name="mar-id" value="<?php echo $row['id']; ?>">
<input type="hidden" name="mar-read" value="New-value">
<input type = "submit" name="update" value="Update with GET">
</form>
<!-- Set the Method to POST as this is what the Controller is Expecting -->
<form action="program/update" method="post">
<input type="hidden" name="mar-id" value="<?php echo $row['id']; ?>">
<input type="hidden" name="mar-read" value="New-value">
<input type = "submit" name="update" value="Update with POST">
</form>
What I used to display the Form in the controller by simply calling the program/index in the Program controller.
public function index() {
$this->load->helper('url');
$data['row'] = array('id' => 2);
$data = $this->load->view('update_view', $data, TRUE);
echo $data;
}
So your Controller is looking for POST and not GET. This can be proven by changing the controller up a bit for debugging.
public function update() {
$this->load->helper('url');
$this->load->model('mdl_update');
$id = $this->input->post('mar-id');
$value = $this->input->post('mar-read');
echo '<h2>POST Values</h2>';
var_dump($id);
var_dump($value);
// ****************************
// These are added in for debugging/Demonstration to show values for the form using the GET method.
$id_get = $this->input->get('mar-id');
$value_get = $this->input->get('mar-read');
echo '<h2>GET Values</h2>';
var_dump($id_get);
var_dump($value_get);
// ****************************
exit('Stopped for Debugging: Method '. __METHOD__.' at Line: '.__LINE__); // Added for Debug
$mar = $this->mdl_update->Update($id, $value);
if ($mar == TRUE) {
redirect(base_url('program/otherpage'), 'refresh');
} else {
redirect(base_url('program/otherpage'));
}
}
So you are looking for POST Data when your form method is set to GET. Please be aware of what you are setting. They must match.
If you want to use GET, you need to use $this->input->get()
The code above will let you test both.
So you now have a POST and GET Form and the controller is setup to demonstrate the two different types. Choose Either GET or POST!. That is up to you on which one you choose.
Issue #2: Expecting a return value from your Model when you are not returning anything.
In your Controller you have the line...
$mar = $this->mdl_update->Update($id, $value);
And in your Model you have...
public function update ($id,$value) {
$data = array(
'status' => $value
);
$this->db->where('id', $id);
$this->db->update('db_table', $data);
}
Your Model Method is not returning anything.
You should always look up what your return values are. I am expecting that your intention was to return the value of the update. Looking through the CI Code itself it appears that if things go wrong it will return FALSE (if the database debug is disabled - learnt something new)
I've added in some debug to assist in viewing what is going on here.
public function update($id, $value) {
$data = array(
'status' => $value
);
$this->db->where('id', $id);
$update_result = $this->db->update('db_table', $data);
echo $this->db->last_query(); // Added for DEBUG
return $update_result;
}
Now I cannot get your code to create new rows as you claim. It's impossible, with this code, to add new rows. So thats happening from something you haven't shown us but that is an aside and not important here.
If we alter the controller to view the model etc (I am only showing the changes ) we would change
exit('Stopped for Debugging: Method '. __METHOD__.' at Line: '.__LINE__);
$mar = $this->mdl_update->Update($id, $value);
To this
$mar = $this->mdl_update->Update($id, $value);
var_dump($mar);
exit('Stopped for Debugging: Method '. __METHOD__.' at Line: '.__LINE__);
If you run this and submit either the GET ( Results are NULL ) or POST, the update will always return TRUE. So your redirect etc needs to be looked at on how you decide on one or the other.
I think you should set your table columns to not allow them to be NULL AND add in some "Validation" in your controller.
ISSUE 3: No Form Validation
CodeIgniter has a Form Validation Class that I suggest you read. This is getting way too long to go into that here...
So as you go through this, you can add/remove debugging to test what is going on and progress it along the way as I have hopefully shown.
if anything is unclear, just ask. I'm sure I may have left something out.

CodeIgniter showing different menu using If statement

I have an error in the variable when I try to get the value it says it was undefined While I have already stored the session of the variable "$level" and sent it to the view but the condition of the variable become undefined, is there anything wrong with the code?
The variable that I get is from the login. Also I have tried to call the $level and it work
I have tried to use foreach and non foreach method still none of these are working
View.php
<?php if($level->level == '1') ?>
<p>Number 1</p>
<?php if($level->level == '2') ?>
<p>Number 2</p>
admin.php
function index(){
$level = $this->session->userdata('level');
$this->load->view('view',$level);
}
Login.php
public function do_login()
{
$u = $this->input->post("user");
$p = md5($this->input->post("pass"));
$cari = $this->model_pesawat->cek_login($u, $p)->row();
$hitung = $this->model_pesawat->cek_login($u, $p)->num_rows();
if ($hitung > 0) {
$data = array('admin_id' => $cari->no_user ,
'admin_user' => $cari->username,
'admin_nama' => $cari->nama,
'level' => $cari->level,
'admin_valid' => TRUE
);
$this->session->set_userdata($data);
redirect('admin','refresh');
}else{
echo "maaf username atau password salah";
}
}
I want the result the if statement will show different value in the view depending on the $level of the user
You need to pass array to the CodeIginter view.
And the array's keys will be used as individual elements in view.
Its similar to extract() function.
So, you should pass $data and add $level into it.
$data['level'] = $level;
$this->load->view('view', $data);
In your view, you can access $level from Controller as $level.
No need to care for $data
In view you can directly use session variable, no need to pass from controller
<p>Number 1</p>
<?php if($this->session->userdata('level') == '2') ?>
<p>Number 2</p>
you should check data in session, whether it's getting stored or not.
echo "<pre>"; print_r($this->session->userdata());

Puzzle with PHP using codeigniter

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.

How to make a search in codeiginiter without "like" paramameter?

Model:
function search()
{
$cari=$this->db->query("select * from uhd_user_order where user_order_reference ");
return $cari->result();;
}
Controller:
function search_keyword()
{
$this->input->GET('cari', TRUE);
$beda['cari'] = $this->order_test_m->search();
$this->load->view('admin/a',$beda);
}
View:
<?php if(count($cari)>0){
foreach ($cari as $row => $test) {
}?>
<?= $test->sendername ?>
<?php
} ?>
I need to make a search, and the result of the view will show up if I put the right code only. Like, if I only search "s", the data from my database will not show up.
How can this be done?
I am not sure what you want, I have some questions about your code, but I can not comment yet. I have to guess what happend:
I think your code works as: Whenever the 'search' button is clicked, all of your user's name in your database will be displayed, right?
Because your model does not use the 'get' data to search in the database
//Your function does not recieve the search string.
//This function uses $string to search in the 'users' table, to finds the name field == $string, and returns only 'name' row.
function search($string){
$query = $this->db->select('name')
->where('name',$string)
->get('users');
//If the result is empty, return false, do nothing.
if($query->num_rows() === 0){
return false;
}
return $query->result();;
}
Controller
function search_keyword()
{
// Call search function with the input data.
// I think here will have some validation
//for example:
//if($this->form_validation->run() == false){
// $this->load->view('errors/error');
//}
$search_string = $this->input->GET('cari', TRUE);
$beda['cari'] = $this->order_test_m->search($search_string);
$this->load->view('admin/a',$beda);
}
View:
// This will ensure the ul will only display when $cari is not empty.
<?php if(count($cari)>0):?>
<ul>
<?php foreach($cari as $row):?>
<li><?php echo $row->name;?></li>
<?php endforeach;?>
</ul>
<?php endif; ?>>

Categories