CodeIgniter Active Record Delete Multiple Records At Once - php

This is one of my controller functions. It grabs all the rows from a database table called 'users' and puts it into an array. It then loads a view called 'deleteuser' with the array data passed through.
function deleteuser(){
$this->load->model('users');
$employees['staff'] = $this->users->getStaff();
$this->load->view('deleteuser', $employees);
}
In the deleteuser view, there's a checkbox type input generated from the array. The form action calls on a function called remove.
<form action="remove" method = "post">
<?php foreach($staff as $row): ?>
<div class="checkbox">
<label>
<input type="checkbox" name="delete[]" value="<?php echo $row->id ?>" />
<?php echo $row->lastName . ", " . $row->firstName; ?>
<br />
</label>
<?php endforeach; ?>
<br />
<br />
<input type="submit" name = "remove" value = "Delete" class = "btn btn-danger btn-lg pull-left" />
</div>
The remove function grabs the delete array from the input and passes it to a model function called deleteUser.
function remove(){
$data = $this->input->post('delete');
$this->users->deleteUser($data);
}
Now this is where I'm running into some trouble. Below is the model function for deleteUser, but it's giving me an undefined offset: 1 error. Any help would be appreciated.
function deleteUser($data)
{
if ($data) {
for ($i = 0; $i <= count($data); $i++)
{
$this->db->where('id', $data[$i]);
$this->db->delete('users');
}
}
}

Though answer by #DamienPirsy is correct in addressing your problem, I would suggest an alternate approach. I would delete all records at once, rather than in a loop. This will minimize your number of queries against the DB.
function deleteUser($data)
{
if (!empty($data)) {
$this->db->where_in('id', $data);
$this->db->delete('users');
}
}

Remove the equal = sign, should be
for ($i = 0; $i<count($data); $i++)
you're fetching 1 element out of bounds. i.e, if count($data) is 4, you're looping: 0 1 2 3 4 ("count minor or equal to 4"), which is five elements indeed :)

Related

Select columns from mysql table by given array in php(CodeIgniter).

I want to select columns form mysql table which I have selected names as input value. In my view, have to select column names as multiple input fields. In this selection option values are equals to column names in my “pass_due” table in database.
<form id="" name=" Passdue " action="<?=base_url('index.php/Passdue_ctrl/select')?>" method="post">
<div >
<input class="date-picker" id="report_date" name="report_date" value="" placeholder="Select Date"/>
<select multiple="" class="chzn-select" id=" " data-placeholder="Select sections " name="table_feilds">
<option value="" />
<option value="below_1" /> Below month
<option value="month_1_3" /> Month 1-3
<option value="month_3_6" /> Month 3-6
<option value="month_6_9" /> Month 6-9
<option value="over_9" /> Over 9 month
</select>
</div>
<div>
<button type="submit" class="btn btn-mini btn-info">Submit</button>
<button type="reset" id="reset" class="btn btn-mini btn-info">Reset</button>
</div>
</form>
This is function in my controller
Function select (){
$fld_name =$this->input->post('table_feilds');
$reportdate=$this->input->post('report_date');
$report=$this->Passdue_model->get_report_part($fld_name,$reportdate);
If($report){
$this->data['report_part']=$report;
$this->data['fld_name']=$fld_name;
$this->load->view('Passdue_other_view',$this->data);
}
}
In my model like this.
function get_report_part1($fld_name,$reportdate)
{
$this->db->select($fld_name);
$this->db->from(‘pass_due’);
$this->db->where('fld_actORinact_date <=',$reportdate);
$query = $this->db->get();
if($query){
return $query->result();
}
}
When I run this code it select all columns from table, not only selected ones. And also it shows error as
Invalid argument supplied for foreach() .
You can use this new model method to retreive data from your db.So insert this method into your model
function getDetail($tablename = '', $columns_arr = array(), $where_arr = array(), $limit = 0, $offset = 0)
{
$limit = ($limit == 0) ? Null : $limit;
if (!empty($columns_arr)) {
$this->db->select(implode(',', $columns_arr), FALSE);
}
if ($tablename == '') {
return array();
} else {
$this->db->from($tablename);
if (!empty($where_arr)) {
$this->db->where($where_arr);
}
if ($limit > 0 AND $offset > 0) {
$this->db->limit($limit, $offset);
} elseif ($limit > 0 AND $offset == 0) {
$this->db->limit($limit);
}
$query = $this->db->get();
return $query->result();
}
}
//These are include within controller methods
$fld_name =$this->input->post('table_feilds');
//you have to send your columns from your multiple select object as array.
//create column array
$arr_columns=array();
for($i=0,$i<=count($fld_name);$i++){
$arr_columns=array_push($fld_name)
}
$reportdate=$this->input->post('report_date');
//create where array
$arr_where=array('fld_actORinact_date <=' => $reportdate);
//retreive data
$datatable=‘pass_due’;
$report=$this->Passdue_model->getDetail($datatable,$arr_columns,$arr_where,0,0);
var_dump($report);
//finally dump_data set .it return array object.Then loop retrieved object.
then this will return what you expect.
Also like to advise you to use generalized model except using separate models for each & every tables.
use below code in form
<select multiple="multiple" class="chzn-select" id=" " data-placeholder="Select sections " name="table_feilds[]"> <!-- use [] for multiple values -->
and I don't see any foreach loop?
and first
echo '<pre>';print_r($fld_name);exit; before
$report=$this->Passdue_model->get_report_part($fld_name,$reportdate);
In your model return the query as follows
return $query->result_array();
In your controller get data by
data['fld_name']=$this->Passdue_model->get_report_part($fld_name,$reportdate);
$this->load->view('Passdue_other_view',$data);
In your view page
foreach($fld_name as $fld_name){?> <th><?php echo $fld_name['column_name '];?></th> <?php }?> </tr> </thead>

importing from mysql column to checkbox php

i am trying to import from mysql column as an exploded values (category id) from table called "products", and print it in a checkbox input, and check if the value (category id) equal to the (category id) in the table called "cats", to set checkbox to "checked", this is my code:
<?php
for($i2=0;$i2<$rowsZ22;$i2++){
//exploding
$catszz2 = explode(",", $bussSubcat);
//foreach start
foreach($catszz2 as $catzz2) {
if($catzz2==$row22[$i2]["id"]){
$ischecked2="checked";
}else{
$ischecked2="";
}
}
//foreach end
?>
<li><input type="checkbox" onclick="getElementById('cats<?=$row22[$i2]["parent"]?>').checked= true;" <?=$ischecked2?> value="<?=$row22[$i2]["id"]?>" name="subcats[]" id="" /> <?=$row22[$i2]["title"]?></li>
<?php
}
?>
the code is checking the last input only (last category)
any help ?
You're running a foreach before you actually output the checkbox...
So, the $isChecked variable is actually changing in your foreach, but only the last value of the loop will be printed.
You need to move your
<li></li>inside the loop of the $isChecked
I'm not sure if this is what you want, but here goes:
<?php
for ($i2 = 0; $i2 < $rowsZ22; $i2++) {
$catszz2 = explode(",", $bussSubcat);
foreach ($catszz2 as $catzz2) {
if ($catzz2 == $row22[$i2]["id"]) {
$ischecked2 = "checked";
} else {
$ischecked2 = "";
}
?>
<li>
<input type="checkbox"
onclick="getElementById('cats<?= $row22[$i2]["parent"] ?>').checked= true;" <?= $ischecked2 ?>
value="<?= $row22[$i2]["id"] ?>" name="subcats[]" id=""/> <?= $row22[$i2]["title"] ?>
</li>
<?php
}
}
?>

php mvc quiz - checking the answers

I'm trying to do a simple quiz using Codeigniter2.2.4 but I'm having some issues with checking the answers.
I have the following structure:
controllers: Guess
models: People
views: guessview, results
in my people class I have a methods to get all questions from the database and to get a random one. I'm having issues checking if the answer is right or no. It always comes back false
function getQuestions()
{
if(!isset($questions))
{
$this->db->select("id, name, choice1, choice2, correctAnswer");
$this->db->from('questions');
$query = $this->db->get();
foreach ($query->result() as $row) {
$questions[] = $row;
}
}
return $questions;
}
function getRandomQuestion()
{
$max = count($this->getQuestions());
$randpos = rand(0, $max-1);
$question = $this->getQuestions()[$randpos];
return $question;
}
And in my controller :
function guess()
{
$answer = $this->input->get('answers',false);
//$questionId = $this->input->get('id',false);
//this will generate random questions.
$newQuestion = $this->people->getRandomQuestion();
$this->load->view('guessview',$newQuestion);
//this is always false
if($answer == $newQuestion->correctAnswer)
{
//do something
}
}
And in my view I have only a form displaying only one question at a time.
//Update
When using the function you provided I'm getting some errors in my controller and view. I try grabbing a question in my controller
$question = $this->people->getRandomQuestion();
//this give me undefined index correctAnswer but should it not have since the database table has the following structure : id, name, choice1, choice2, correctAnswer ?
if($question['correctAnswer'] == $answer)
{
}
Also when I want to pass data to the view i.e
$question = $this->people->getRandomQuestion();
$data['question'] = $question;
$this->load->view('guessview',$data);
And in my view for the form values I tried like this: $question['name'], $question['id'] and I get undefined index name,id etc.
My form from guessview.php
<form id= "form1" class="form" action="<?php echo base_url();?>guess/people" method='POST'>
<input type=hidden name=id value="<?php echo $question['id'] ?>">
<label><?php echo $question['name'] ?>
<div class="radio">
<label>
<input type="radio" id='rad1' name="answers" value="<?php echo $question['choice1'] ?>">
<?php echo $question['choice1'] ?>
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="answers" value="<?php echo $question['choice2'] ?>">
<?php echo $question['choice2'] ?>
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="answers" value="<?php echo $question['correctAnswer'] ?>">
<?php echo $question['correctAnswer'] ?>
</label>
<div>
<input type=submit name="sub" value="Answer">
</div>
</form>
The problem why I posted was regarded to the controller function. It seems that when I try to check if the user answered correctly is always false. Like what the user answered the previous question get compared with the correctAnswer of the current question.
I tried getting the input of the radio button and id(put in a hidden field)
if these were returning false it meant that no questions are display and displayed first question. else if there was input then get the question based on the id and compare the question's correctAnswer to what the user selected.(But like I said above it would always be false). I will post the method when I get home.
You can do it in single Model function
function getRandomQuestion()
{
$sql = "SELECT * FROM questions ORDER BY RAND() LIMIT 1 )";
$query = $this->db->query($sql);
$result = $query->result_array();
$count = count($result);
if (empty($count) ||$count > 1) {
echo "Inavliad Question";
}
else{
return $result;
}
}

How to deal with unchecked checkbox array value without javascripts?

Suppose I have a form like this, where checkboxes are repeating fields:
<form action="" method="post">
<?php for($i=0; $i<3; $i++) { ?>
<input type="checkbox" name="ch[]" value="1">
<?php } ?>
<button type="submit" name="submit">submit</button>
</form>
I'm on WordPress and using custom meta boxes for dealing with it. So I declared the form within the callback function of the metabox, and receiving the values in another save function that's hooked with save_post and new_to_publish action hooks.
So what's happening: when I click on the button, the metabox callback submitted the form, and the hooked function receives it. (Can be visible at add_meta_box() WordPress Codex) Suppose my save function contains:
<?php
if( isset($_POST['submit']) ) {
$chb = $_POST['ch'];
$result = array();
foreach ($chb as $cb) {
$result[] = array( 'isactive' => $cb );
}
var_dump($result);
}
?>
It's showing that, checkboxes are not returning any value when unchecked. I considered all the server-side solutions mentioned here: Post the checkboxes that are unchecked
PROBLEM is, whenever the form is submitted, it's taking the checkboxes' values to an array(), so I can't check the array values like:
if( !isset( $_POST['ch'] ) || empty( $_POST['ch'] ) ) {
$chb = 0;
} else {
$chb = 1;
}
I also tried hidden field with 0 value, accompanied with array_unique(), but nothing seems work for me.
How can I deal with unchecked checkboxes in an array so that they can't be null, and my foreach can loop through all of 'em and store data accordingly, and correct?
I want to avoid JavaScripts solutions.
If you name the checkboxes with an index in them, like so:
<input type="checkbox" name="chk_<?php echo $i ?>" value="1">
Then you could loop through them like so:
<?php
$chkBoxes = array();
foreach ($_POST as $k => $v) {
if (strpos("chk_",$k) === 0) {
$cbIndex = str_replace('chk_', '', $k);
$chkBoxes[$cbIndex] = $v;
}
}
Then to test if a checkbox was checked and sent to the server, you could use:
<?php
if (isset($chkBoxes[$cbIndex]))
Remember - the value of the checkbox is only sent if it was checked: Does <input type="checkbox" /> only post data if it's checked?
Add a hidden field in the form with the number of checkboxes, and use the index $i for the array ch[]:
<form action="" method="post">
<input type="hidden" name="num" value="<?= $num = 3 ?>">
<?php for($i=0; $i<$num; $i++) { ?>
<input type="checkbox" name="ch[<?= $i ?>]" value="1">
<?php } ?>
<button type="submit" name="submit">submit</button>
</form>
Then:
<?php
if( isset($_POST['submit']) ) {
$chb = $_POST['ch'];
$num = $_POST['num'];
$result = array();
for($i=0; $i<$num; $i++) {
$result[$i]['isactive'] = isset($chb[$i]) ? 1 : 0;
}
var_dump($result);
}
?>
first of all i copied ideas from many people inside this forum! i only synthesized the way!
my function to get data from my base located inside the $anoigmata class:
function getall() {
$data = $this->_db->get('<table_name>', array('ID', '>=', 0));
$results = $data->results();
$rows = $data->count();
return array($results, $rows);
}
code inside the create function to save all the secondary options that are not presented on the site.
$fields_Κ = array('history' => serialize(array(
'checkboxes' => Input::get('checkboxes')
)),
);
$data = $this->_db->insert('ΚΕΛΥΦΟΣ', $fields_Κ);
return true;
the php-html code that shows the result
<form method="post">
<div class="form-group">
<label for="checkboxes[]">checkboxes title</label><br>
`<?php
for ($i=0; $i<$anoigmata->getall()[1]; $i++) {
echo "
<input type='hidden' name='checkboxes[$i]' value='0' />
<input type='checkbox' id='checkboxes[$i]' name='checkboxes[$i]' value='".$anoigmata->getall()[0][$i]->ΕΜΒΑΔΟΝ."' />".$anoigmata->getall()[0][$i]->ΠΕΡΙΓΡΑΦΗ."<br>";}?>`
`</div><button type="submit" class="btn btn-success">Submit</button></form>`
***ΕΜΒΑΔΟΝ and ΠΕΡΙΓΡΑΦΗ are the row names from my table that i'm saving!!!
i hope i helped a little..!

Setting variable and string from POST with loop

Currently I have 100 text input boxes named contact0 through contact101. I am trying to get the Post data and name each string to itself. Meaning $contact0 = $_POST['contact0'];all the way up to $contact101 = $_POST['contact101']; there has to be a simpler way to set them in a loop or something. Overall the end result is I just want the data entered in the textbox to become the value of the textbox when submitted. Any suggestions will help I might be doing this wrong for the results I want.
for ($i = 0; ;$i++){
if($i < 101){
$contact.$i = $_POST['contact'].$i;
echo $contact.$i;
}
else{
break;
}
}
for ($i = 0; $i <= 101; $i++){
${"contact".$i} = $_POST['contact'.$i];
echo ${"contact".$i};
}
You may want to consider amending your HTML form. Rather than create 100 new variables, you can assign all the contacts to an array and then reference them with the array index.
HTML
<input type="text" name="contacts[]" value="Contact 1 name"/>
<input type="text" name="contacts[]" value="Contact 2 name"/>
// etc...
PHP
$contacts = $_POST['contacts'];
var_dump($contacts);
// prints array(0 => 'Contact 1 Name', 1 => 'Contact 2 Name'...
As it now an array, you can reference the contact e.g. $contacts[34] and know it will be a valid entry.
EDIT
A working example:
<?php
if (isset($_POST['contacts'])) {
$contacts = $_POST['contacts'];
echo "<p>The contacts are below:</p>";
print_r($contacts);
} else {
echo "<p>Please enter the contacts</p>";
}
?>
<form method="post" action="">
<?php for($x = 0; $x < 100; $x++): ?>
<input type="text" name="contacts[]" value="<?php echo (isset($contacts[$x])) ? $contacts[0] : ''; ?>"/>
<?php endfor; ?>
<input type="submit" name="submit" value="submit"/>
</form>
Edit 2
I have now made the form a loop, meaning it will create all our contact inputs for us. On top of this, if we have already posted the form each field will have the correct contact values.
If you are not aware of the syntax, echo isset($contacts[$x])) ? $contacts[$x] : ''; is a ternary operator which is a one line if/else statement.
Which can also be tested here: http://phpfiddle.org/api/run/ugb-cta

Categories