Conditional select from a table using codeigniter - php

Im trying to make a select which only shows some information (a conditional select).
I mean, this is my table "usuarios":
"usuarios" includes:(id,username,name,lastname,password,type,status,date)
Take a look:
My goal is to make a select that only shows the users with "type" = 1 AND "status" = 1
Take a look:
I have a done a select but it shows every usernames, it does not validates anything :/.
My program shows this, and it is not correct because it does not validate anything :/
Here is my code:
My controller file:
public function edit($ID){
$data['usuarios'] = $this->Crudmodel->get_usuarios();
$data['record']=$this->Crudmodel->get_id_row($ID);
$this->load->view('edit',$data);
}
My model file:
public function get_usuarios() {
$this->db->select('c.*')
->from('usuarios c');
$q = $this->db->get();
return $q->result();
}
My "edit" file:
<h2 align="center">UPDATE</h2>
<form method="post" action='<?php echo site_url('Home/saveupdate'); ?>'>
<tr>
<td><input type="text" hidden name="txtid" value="<?php echo $record->id ?>"/></td>
</tr>
<tr>
<td>
<select name="txtcarr">
<?php foreach($usuarios as $item):?>
<option value="<?php echo $item->id;?>"><?php echo $item->username;?></option>
<?php endforeach;?>
</select>
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Save"/></td>
</tr>
Dont know whatto do :/

Why not only select the rows you want? Will it work as you expect if you put this in your model?
public function get_usuarios() {
$this->db->select('id, username')
->from('usuarios')
->where(array('status'=>1, 'type'=>1));
$q = $this->db->get();
return $q->result();
}

Related

Making a table with foreach, trying to submit data using each table row

So its been over 10 years since writing any code what so ever so i might be way off here. I have a table showing all students in a classroom populated by a foreach loop with an added box to input their grade. I need 1 submit button to insert one new row per student in the grades table in my database with their grade and the assignment name that is selected above.
I know i need to identify each grade value im just unsure how and it's only posting the person in the last row.
global $wpdb;
$asnames = $wpdb->get_results( "SELECT * FROM assignments" );
$results = $wpdb->get_results( "SELECT * FROM enrolled" );
?>
<div class="container"><center>
<form action ="<?php echo $_SERVER['REQUEST_URI']; ?>" method ="post">
<table class="form-table" id='topper'>
<tbody>
<tr>
<th>Assignment Name</th>
</tr>
<tr>
<td>
<select name="Assignment">
<?php foreach($asnames as $asname) { ?>
<option value="<?php echo $asname->id ?>"><?php echo $asname->assign_name ?></option>
<?php
} ?>
</select>
</td>
</tr>
</tbody>
</table></center>
</div>
<br><br>
<div class="container"><center>
<form action ="<?php echo $_SERVER['REQUEST_URI']; ?>" method ="post">
<table class="form-table" id='student'>
<tbody>
<tr>
<th>Students Name</th>
<th>Points</th>
</tr>
<?php foreach($results as $row){ ?>
<tr>
<td><?php echo "$row->student_name" ?></td>
<td><input type="text" class="regular-text" name="Grade"></td>
</tr>
<?php } ?>
<!-- </tbody> -->
</table>
<p><input type="submit" name="submitinsert" id="submitinsert" class="button button-primary" value="Submit"/></p> </form>
</center></div>
<?php
if ($_POST['submitinsert']){
$result = $wpdb->insert(
'grades',
array(
"student_name" => $row->student_name,
"assignment_id" => $asname->id ,
"grade" => $_POST['Grade']
)
);
}
I cant seem to get it to grab each row as it is in the table to insert, only the last row gets put in.
EDIT: I got the grade input worked out now just trying to get each loop put into the database with the single submit button.

Enter data from attendance sheet into phpmyadmin

Inserting multiple record in phpmyadmin att table keeping all the information same except attendance and student id after clicking the submit button.Its taking only one last row without attendance status.I'm fetching attendance sheet from database.I have been stuck here in my first php project.
faculty panel
<form action="<?php $PHP_SELF ?>" method="post">
<li><b>Select Courses :</b> <select name="courses" id="courses" class="form-
control action" >
<option value="">Courses</option>
<?php echo $courses; ?></select></li><br/>
<li><b>Select Semesters :</b> <br><select name="semesters" id="semesters"
class="form-control action" >
<option value="">Semesters</option></select></li><br/>
<li><b>Select Subjects :</b><br> <select name="subjects" id="subjects"
class="form-control " >
<option value="">Subjects</option></select>
<br/>
<li><b>Session No:<b><br/><input type="text" name="session_no"
id="session_no" placeholder ="Session No" class="form-control">
<br>
<label class="control-label" for="date">Date</label>
<br/>
<input class="form-control" id="date" name="date" placeholder="DD/MM/YYYY"
type="date"/>
<br/>
<li><b>Enter time:</b></li><br/>
From :<input type="time" name="time_from" id="time_from" class="form-
control"/> </li><li>
<br/>
To :<input type="time" name="time_to" id="time_to" class="form-control"/>
</li></div>
<br>
<li><label class="btn btn-info">Display attendance sheet</label> </li>
<br/>
//attendance table
<table id = "table" class = "table table-bordered">
<thead class = "alert-info">
<tr>
<th>Student ID</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Present</th>
<th>Absent</th>
</tr>
</thead>
<tbody>
<?php
$q_student = $conn->query("SELECT * FROM `student`")
or die(mysqli_error());
while($f_student = $q_student->fetch_array()){
?>
<tr>
<td><input name="student_no" value="<?php echo
$f_student['student_no']?>" class="form-control"
readonly/></td>
<td><?php echo $f_student['firstname']?></td>
<td><?php echo $f_student['lastname']?></td>
<td><input type="radio" name="attendance[<?php echo
$f_student['student_no']; ?>]" value="1"
class="form-control"></td>
<td><input type="radio" name="attendance[<?php echo
$f_student['student_no']; ?>]" value="0"
class="form-control"></td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php
//Insert Record into attendancetable
if(isset($_POST['submit']))
{
foreach ($_POST['attendance'] as $attendance){
$faculty_id =
mysqli_real_escape_string($conn,$_SESSION['faculty_id']);
$student_no =
mysqli_real_escape_string($conn,$_POST['student_no']);
$courses = mysqli_real_escape_string($conn,$_POST['courses']);
$semesters = mysqli_real_escape_string($conn,$_POST['semesters']);
$subjects = mysqli_real_escape_string($conn,$_POST['subjects']);
$session_no = mysqli_real_escape_string($conn,$_POST['session_no']);
$date = mysqli_real_escape_string($conn,$_POST['date']);
$time_from = mysqli_real_escape_string($conn,$_POST['time_from']);
$time_to = mysqli_real_escape_string($conn,$_POST['time_to']);
$attendance=var_dump($_POST['attendance']);
$conn=mysqli_connect("localhost","root","","db_sars");
$ins="INSERT INTO att( faculty_id,student_no,courses,semesters,subjects,session_no,date,time_from,time_to,attendance_status)
VALUES ('$faculty_id','$student_no','$courses','$semesters','$subjects','$session_no','$date','$time_from','$time_to','$attendance')";
}
if(#mysqli_query($conn,$ins))
{
echo "inserted";
}
else
{
die(#mysqli_error());
}
}
?><input type="submit" name="submit" value="Submit Form" class="btn btn-info"></form>
In the code you posted, you are not assigning the attendance data ($_POST['attendance']) to the $attendance variable due to use of var_dump.
You wrote:
$attendance=var_dump($_POST['attendance']);
From the php manual for var_dump:
Return Values
No value is returned.
Instead, try formatting this line like you did all the rest:
$attendance = mysqli_real_escape_string($conn,$_POST['attendance']);
Adding multiple students at a time- update
It appears that you are printing each student id in the front end table. I think that would be a better field to loop with. However, with your current front end code, it is creating a new post variable for each student id. Instead you probably want this instead:
<td><input name="student_no" value="StudentID[<?php echo $f_student['student_no']?>]" class="form-control" readonly/></td>
Note how this turns the student id into an array of student ids rather than a ton of different variables of each student ID.
Then for your foreach:
foreach ($_POST['StudentID'] as $StudentID) {
$StudentID is now updated for each iteration and allows you to look up the appropriate index in the other arrays. And you would change the pertinent rows as:
$student_no = mysqli_real_escape_string($conn,$StudentID); // The student ID is set by as in foreach
$StudentAttendance = $_POST['attendance'][$StudentID]; // Get the attendance status by looking up the student by student id in the attendance array
$attendance=mysqli_real_escape_string($conn,$StudentAttendance); // Escape input to avoid table disasters (reference Little Bobby Tables)
I haven't tested your code and understand that there is a lot more going on than this. However, it's probably best to tackle one thing at a time. What you have to do is create a loop to go over each student, and each field that you want to collect should be posted as an array with an index for each student by their student id.
Using var_dump is useful for understanding what a variable contains (for instance, it would help us to see what your variables contain if you would post the var_dump output with your question). If you have error messages, please post them as it helps guide us in the right direction as we attempt to help you out.

Codeigniter, Passing Inputs of Array and then display the result

Excuse me if this question is already asked everywhere, but i cant find answer that worked.
So I have a dynamically generated table, which is generated by selecting rows from a table in a database.
This is the view file that create the table.
all rows except the heading are created based on how many data found in the table in a database, so, all the inputs are have name like
<form class="form-horizontal" role="form" id="formDtKryw" method="POST" action="updKryw">
<div class="table-responsive form-group row">
<table class="table table-hover table-condensed table-bordered">
<thead class="text-center">
<tr>
<th>No</th>
<th>Nama</th>
<th>Telepon</th>
</tr>
</thead>
<tbody>
<?php $no = 0;
foreach ($dftr_crKryw as $data_crKryw):
$no_ktp[$no] = $data_crKryw->no_ktp;
?>
<input type="hidden" name="no_ktp[<?php echo $no; ?>]" id="no_ktp[<?php echo $no; ?>]" value="<?php echo $data_crKryw->no_ktp; ?>">
<tr>
<td><?php echo $no+1; ?></td>
<td><?php $this->db->select('nama,')->from('dt_prbd')->where('no_ktp', $data_crKryw->no_ktp);
$qry = $this->db->get();
if ($qry->num_rows() > 0) {
foreach($qry->result() as $data):
echo $data->nama;
endforeach;
}
?></td>
<td><?php
if ($data_crKryw->memo == NULL) {
?>
<select class="form-control input-sm" name="memo[<?php echo $no; ?>]" id="memo[<?php echo $no; ?>]">
<option value="">---Pilih---</option>
<option value="Memo 1">Memo 1</option>
<option value="Memo 2">Memo 2</option>
<option value="Memo 3">Memo 3</option>
</select>
<?php
}
else {
echo $data_crKryw->memo;
}
?></td>
</tr>
<?php
$no++;
endforeach;
}
?>
<input type="hidden" name="totData" id="totData" value="<?php echo $no; ?>">
<tr>
<td colspan="11" align="right"><button type="submit" id="submit" class="btn btn-primary">Simpan Data</button> <button type="reset" class="btn btn-danger">Hapus Form</button></td>
</tr>
</tbody>
</table>
</div>
</form>
This is the Controller that should catch the inputs
function updKryw(){
$totData = $this->input->post('totData');
$no_ktp = $this->input->post('no_ktp');
$memo = $this->input->post('memo');
$frmUpdKryw = array(
'totData' => $totData,
'no_ktp' => $no_ktp,
'memo' => $memo
);
$this->load->view('display_data', $frmUpdKryw);
}
And this is the view file that suppose to view all the captured information from the form
<html>
<head></head>
<body>
<?php
for($x = 0; $x < $totData; $x++){
echo $totData . "<br>";
echo $no_ktp[$x] . "<br>";
echo $memo[$x] . "<br>";
}
?>
</body>
</html>
All that displayed is only the $totData, and the $no_ktp[$x] and $memo[$x] is not display anything.
Anyone can help please if there is any error in my code or my logic.
Thanks in advance.
=========================================================================
edit: i started to think that my php engine is broken. why?
even this simple form doesn't display anything.
form.php
<form name="myForm" method="post" action="go.php">
<input type="text" name="name" value="firstname">
<input type="text" name="addr" value="firstaddr">
<button type="submit" name="submit" id="submit">save</button>
</form>
go.php
$name = $_POST[name];
$addr = $_POST[addr];
echo $name;
echo $addr;
First I recommend debug before saving data to $frmUpdKryw array
$this->input->post(NULL, TRUE); // returns all POST items with XSS filter
$this->input->post(); // returns all POST items without XSS filter
Then if data is not empty, before
$this->load->view('display_data', $frmUpdKryw);
add
var_dump($frmUpdKryw);
if all is good here, then to debug in beginning of the view
var_dump($totData);
var_dump($no_ktp);
var_dump($memo);
If all is good here then problem is in your loop, so you will need just fix it. Either you will know where you have problems:
failed with sending data with POST
failed with saving to new variable
failed with sending data to view
and last failed with loop
Hope it will help
when I solve another problem within the same app, this problem is fixed too, the problem is not in the code or logic. all codes are works as expected.
here are the link for the solution. not the solution that I expect, but its working.
The Solution
thanks to Abdulla and Oleg Sapishchuk

Store PHP/SQL foreach form items in variables

Sorry I'm a bit of a noob when it comes to PHP but I just wondered if someone had an idea on how I could solve this PHP/SQL problem.
I have a PDO statement that gets all users from a database.
With the array of users from the database I create a foreach loop to display all of the users in a table which I want to use to select a specific user, enter a number in the row of the user I select, then click submit and store the users name and also the number. I will use this information to populate another database later.
My question is, I cant seem to reference the user or the number in the table to extract the user and number I enter. When I try and request the numbered entered in the index.php, it will only ever display a number if I enter a number for a the final user in the table. When I try and view the FullName it never works and I get 'Undefined index: FullName' error.
I also specified to 'POST in the form but it doesnt seem to be doing that.
Does anyone have any ideas?
Thanks
//function.php
function getName($tableName, $conn)
{
try {
$result = $conn->query("SELECT * FROM $tableName");
return ( $result->rowCount() > 0)
? $result
: false;
} catch(Exception $e) {
return false;
}
}
//form.php
<form action "index.php" method "POST" name='form1'>
<table border="1" style="width:600px">
<tr>
<th>Name</th>
<th>Number Entered</th>
<tr/>
<tr>
<?php foreach($users as $user) : ?>
<td width="30%" name="FullName">
<?php echo $user['FullName']; ?>
</td>
<td width="30%">
<input type="int" name="NumberedEntered">
</td>
</tr>
<?php endforeach; ?>
</table>
<input type="submit" value="submit"></td>
</form>
//index.php
$users = getName('users', $conn);
if ( $_REQUEST['NumberedEntered']) {
echo $_REQUEST['NumberedEntered'];
echo $_REQUEST['FullName'];
}
The variable FullName isn't transmitted by your form to index.php. Only values of form elemnts are sent. You can add a hidden form field, that contains FullName like this:
<input type="hidden" name="FullName" value="<?php echo $user['FullName']">
But your second problem is, that your foreach loop will create several input fields with the exact same name. You won't be able to recieve any of the entered numbers, except the last one. have a look at this question for possible solutions.
Update
Putting each row in individual form tags should solve your problem:
<?php foreach($users as $user) : ?>
<form action="index.php" method="POST">
<tr>
<td align="center" width="40%" >
<?php echo $user['FullName']; ?>
<input type="hidden" name="FullName" value="<?php echo $user['FullName']; ?>" />
</td>
<td width="30%">
<input name="NumberedEntered"/>
</td>
<td>
<input type="submit" value="submit"/>
</td>
</tr>
</form>
<?php endforeach; ?>

Showing Data and Image for Form Edit in codeigniter

I have my car models in a edit form which users can edit and delete a car.
When user clicks on edit they could see the car, model, year, price on the edit form and make new changes and submit. I want the uploaded image to show up and edit as well. I know form_input() wont bring the image to show. I tried everything but it wont display in my edit form. Here is my code, thanks!
controller:
public function input($id = 0) {
$this->load->helper('form');
$this->load->helper('html');
$this->load->model('model_users');
/*
if($this->input->post('submit')) {
$this->model_users->entry_insert();
}
$data = $this->books_model->general();
*/
if((int)$id > 0) {
$query = $this->model_users->get($id);
$data['fid']['value'] = $query['id'];
$data['fcar_make']['value'] = $query['car_make'];
$data['fcar_model']['value'] = $query['car_model'];
$data['fcar_year']['value'] = $query['car_year'];
$data['fcar_lease']['value'] = $query['car_lease'];
$data['fcar_payment']['value'] = $query['car_payment'];
$data['fimgpath']['value'] = $query['imgpath'];
}
if($this->session->userdata('is_logged_in')) {
$this->load->view('edit_car',$data);
}
else {
redirect('main/restricted');
}
}
Model:
function get($id) {
$this->db->where(array('id'=>$id));
$query = $this->db->get('cars');
return $query->row_array();
}
view
<tr>
<td>Car Lease:</td>
<td><input type="text" class="textbox" tabindex="6" name = "<?php echo form_input($fcar_lease); ?></td>
<td> </td>
</tr>
<tr>
<td>Car Payment:</td>
<td><input type="text" class="textbox" tabindex="6" name = "<?php echo form_input($fcar_payment); ?></td>
<td> </td>
</tr>
<tr>
<td>Car Image:</td>
<td><input type="file" name=""<?php echo form_input($fimgpath); ?>" size="20" /></td>
<td> </td>
</tr>
You can't show image or image path in file upload field, instead of that just show the image underneath the file upload field (like you display it in the front-end) and if user re uploads the image, delete existing one, upload new one and update the image name in the DB.
Additionally you can give a delete button to delete the image on the same interface (may underneath the current image).

Categories