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>
Related
I want to input multiple data to database using array, but I got an error message. The code are in the following bellow :
ClusterController
$jawaban = $request->jawaban;
$data = [];
if($jawaban != null || $jawaban == false){
for($i=1; $i<=count($jawaban['jawaban']); $i++){
$data[] = array('jawaban' => $jawaban[$i]['jawaban']);
}
$store = Soal::where('cluster_id', $id)->update($data);
return dd($store);
}
showexam.blade.php
<form action="/jawaban/store/{{$model[$i]->id}}" method="post" enctype="multipart/form-data">
#csrf
<table id="datatable" style="width:100%">
<tbody>
<tr>{{$i+1}}. </tr>
<tr>{{$model[$i]->soal}}</tr>
<ol type="A" style="">
<li> {{$model[$i]->A}}</li>
<li> {{$model[$i]->B}}</li>
<li> {{$model[$i]->C}}</li>
<li> {{$model[$i]->D}}</li>
<li> {{$model[$i]->E}}</li>
</ol>
<input list="browsers" name="jawaban[]">
<datalist id="browsers">
<option value="A">
<option value="B">
<option value="C">
<option value="D">
<option value="E">
</datalist>
#endfor
<button type="submit" class="btn btn-primary text-right" id="modal-btn-save">Done</button>
</form>
count($jawaban['jawaban'])
You already have an array called jabawan that you retrieved with $jawaban = $request->jawaban;
That jabawan will have a normal counting array $jabawan = ['A', 'B']
It will not have an index called jabawan.
If you had done something like
$jabawan = post();
You could use your code, but you can just use
for($i=0; $i<count($jawaban); $i++){
$data[] = array('jawaban' => $jawaban[$i]);
}
Change Soal::where('cluster_id', $id)->update($data);
into
if ($soal_model = Soal::find( $id )) {
$soal_model->update($data);
}
The problem is that you're never calling get() on the query object, or a first() on the collection that the get() returns.
By using find() You get an object back or null if it doesn't exist.
By wrapping that in an if statement the update will only be executed on an existing object, preventing errors on trying to update a null value.
Also, you cannot return a dd().
dd stands for 'dump and die' I believe, at least that is what I read into it because that's what it does.
It dumps the data and then kills the process. So all laravel return handlers won't get called after your dd() call. You killed the process.
I'm trying to put values into a MySQL table like this one:
|---sbjct_name---|---level---|
|---------- Physics ----------|----Level 1-----|
|---------- Physics ----------|----Level 2-----|
|---------- Physics ----------|----Level 3-----|
|---------- Calculus ---------|----Level 1-----|
|---------- Calculus ---------|----Level 2-----|
(I don't know how to make table but I guess u get the idea)
Let say I'm going to put "Math" into sbjct_name column alongside with "Level 1", "Level 2", "Level 3" values into the level column.
The basic idea is from this pict (selecting value for a same input text value).
Instead of inserting "Math" multiple times for each level,
I'm trying to make it one time submit with checkbox tag. It will be something like this pict (with checkbox).
I don't have any idea how to make this happen (or if it possible in CI).
This is some code from my Controller,
public function add_subject()
{
$data = array();
if ($this->input->post('savebttn'))
{
$this->form_validation->set_rules('sbjct_name', 'Subject Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('level', 'Level', '|required|is_natural');
$this->form_validation->set_error_delimiters('<span class="fielderror">','</span>');
if ($this->form_validation->run() == FALSE)
{
$data['reset'] = FALSE;
}
else
{
//I don't know what to do here
//I don't know what to do here
//I don't know what to do here
//I don't know what to do here
}
}
$data['level'] = $this->admin_model->get_checkbox_option('level', 'lvl_id', 'lvl_name');
$data['page'] = 'createsubject';
$this->load->view('admin/main', $data);
}
This is a checkbox view function in the Model,
public function get_checkbox_option($table, $id, $name, $selected=0)
{
$query = $this->db->get($table);
$select= '';
if ($query->num_rows() > 0)
{
foreach ($query->result_array() as $row)
{
$selected_option = ($selected == $row[$id]) ? 'selected = "selected" ':' ';
$select .='<input type="checkbox" name="level" value="'.$row[$id].'" '.$selected_option.'>'.$row[$name].'<br>';
}
}
return $select;
}
This is the form on the View,
<form action="" method="post" id="createcategoryform">
<table>
<tbody>
<tr>
<td><div class="label">Subject Name</div></td>
<td><div class="input">
<input type="text" name="sbjct_name" size="39" class="ui-corner-all input-text validate[required]">
<?=form_error('sbjct_name');?>
</div></td>
</tr>
<tr>
<td><div class="label">Level</div></td>
<td><div class="input-text ui-corner-all validate[required]">
<?=(isset($level)) ? $level: '';?>
</div><?=form_error('level');?></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Save" name="savebttn" class="input-button ui-corner-all ui-state-default"></td>
</tr>
</tbody>
</table>
</form>
I will be grateful if you can give any clue. :D
first
make your checkbox as an array so it look like this
$select .='<input type="checkbox" name="level[]" value="'.$row[$id].'" '.$selected_option.'>'.$row[$name].'<br>';
give attention to the name. yours name="level" and mine name="level[]"
, then you can grab all level as one variable
second
make your controller like this
if ($this->form_validation->run() == FALSE)
{
$data['reset'] = FALSE;
}
else
{
// make array container for input batch
$insertData = array();
if(!empty($this->input->post('level'))) {
foreach($this->input->post('level') as $level) {
$tempArray = array(
'sbjct_name' => $this->input->post('sbjct_name'),
'level' => $level
);
array_push($insertData, $tempArray);
}
// it's better to put this in model
// but for example purpose I put it there
$this->db->insert_batch('table', $insertData);
//do what you want to do here
}
}
hope you get the point #nasamikhail
I was wondering how to make a search form where user has 3 options to search with
Search By age (dropdown 18-25 & 26-40)
Search By gender (male or female)
Search By name
In my code, when I click "Submit" with blank fields, it's throwing all data which i don't it to:
<?php
$output = NULL;
if (isset ( $_POST ['submit'] )) {
// Connect to database
$mysqli = new Mysqli ( "localhost", "root", "2222", "matrimonialPortal" );
$search = $mysqli->real_escape_string ( $_POST ['search'] );
// Query the databse
$resultSet = $mysqli->query ( "SELECT * FROM mp_user WHERE name LIKE '%$search%' OR email LIKE '%$search%' OR salutation LIKE '%$search%' OR id LIKE '%$search%'" );
if ($resultSet->num_rows > 0) {
while ( $rows = $resultSet->fetch_assoc () ) {
$name = $rows ['name'];
$email = $rows ['email'];
$output .= "::<strong>The Details of your search</strong> ::<br /> Name: $name<br /> Email:$email<br /><br /> ";
}
} else {
$output = "Oops No results Found!!";
}
}
?>
<!-- The HTML PART -->
<form method="POST">
<div>
<p>
Search By name: <input type="TEXT" name="search" /> <input
type="SUBMIT" name="submit" value="Search >>" />
</p>
</div>
<div>Search By Age :
<select name="age">
<option></option>
<option value="18-20">18-20</option>
<option value="20-25">20-25</option>
</select><input type="SUBMIT" name="submit" value="Search >>" />
</div>
<br />
<div>
Search By Gender:
<select name="salutation">
<option></option>
<option value="0">--- Male ---</option>
<option value="1">--- Female ---</option>
</select> <input type="SUBMIT" name="submit" value="Search >>" />
</div>
<br> <br>
</form>
<?php echo $output; ?>
It seems like you are new to PHP. Here is a solution for you.
First HTML PART. Here use "action" which means that the page will locate the file and process data. For example action="search_process.php". But if you are processing the data from the same page use $_SERVER['PHP_SELF'];
<!-- The HTML PART -->
<form method="POST" action="$_SERVER['PHP_SELF']"> // here it will load the self page
<div>
<p>
Search By name: <input type="text" name="search_name" />
Search By age: <input type="text" name="search_age" />
Search By gender: <input type="TEXT" name="search_gender" />
<input type="submit" name="submit_name" value="Search >>" />
</p>
</div>
Now the PHP part:
<?php
if(isset($_POST['submit_name'])
{
//What happens after you submit? We will now take all the values you submit in variables
$name = (!empty($_POST['search_name']))?mysql_real_escape_string($_POST['search_name']):null; //NOTE: DO NOT JUST USE $name = $_POST['search_name'] as it will give undefined index error (though your data will be processed) and will also be open to SQL injections. To avoid SQL injections user mysql_real_escape_string.
$age = (!empty($_POST['search_age']))?mysql_real_escape_string($_POST['search_age']):null;
$gender = (!empty($_POST['search_gender']))?mysql_real_escape_string($_POST['search_gender']):null;
//Now we will match these values with the data in the database
$abc = "SELECT * FROM table_name WHERE field_name LIKE '".$name."' or field_gender LIKE '".$gender."' or field_age LIKE '".$age."'"; // USE "or" IF YOU WANT TO GET SEARCH RESULT IF ANY OF THE THREE FIELD MATCHES. IF YOU WANT TO GET SEARCH RESULT ONLY WHEN ALL THE FIELD MATCHES THEN REPLACE "or" with "and"
$def = mysql_query($abc) or die(mysql_error())// always use "or die(mysql_error())". This will return any error that your script may encounter
//NOW THAT WE HAVE GOT THE VALUES AND SEARCHED THEM WE WILL NOW SHOW THE RESULT IN A TABLE
?>
<table cellspacing="0" cellpadding="0" border"0">
<tr>
<th>Name</th>
<th>Age</th>
<th>Gender</th>
</tr>
<?php while($row = mysql_fetch_array($def)) { // I HAD MISSED OUT A WHILE LOOP HERE. SO I AM EDITING IT HERE. YOU NEED TO USE A WHILE LOOP TO DISPLAY THE DATA THAT YOU GOT AFTER SEARCHING.
<tr>
<td><?php echo $row[field_name]; ?></td>
<td><?php echo $row[field_age]; ?></td>
<td><?php echo $row[field_gender]; ?></td>
</tr>
<?php } ?>
</table>
<?php } ?>
A perfect solution for your query. All the best.
Well i cant give you the whole code, but here are the few solutions..
Use 3 different forms with 3 different submit buttons.
Use radio buttons on html form, and make a check on PHP side and perform operations depending upon what or which radio is selected.
Use a button instead of submit, radio buttons, hidden fields, and pass data to different php page on form submit (this can be lengthy).
Well you have options.
You can replace your code
if ($resultSet->num_rows > 0) {
with this
if ($resultSet->num_rows > 0 and trim($search) != "") {
so it will not show all results if your input box is empty
hope this will help you
Edit
here is an example you can get idea
$qry = "SELECT * FROM test WHERE 1=1";
if($purpose!="")
$qry .= " AND purpose='$purpose'";
if($location!="")
$qry .= " AND location='$location'";
if($type!="")
$qry .= " AND type='$type'";
and for age
if ($age!='') {
$qry .= " AND age between ".str_replace('-',' and ',$age);
}
When you POST a blank variable and Query with %$search% and 'OR' other criteria, sql matches all records with space in column Name ! So you will have to use some variation of;
If(empty($POST['search']){ ['Query witbout Name parameter']} else{['Query with Name parameter']}
As for converting DOB to match age range. You will have to use
SELECT TIMESTAMPDIFF
answered here
calculate age based on date of birth
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;
}
}
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 :)