I am trying to insert multiple rows to my database using a single query. I saw lots of questions related to this but they dont work for me.
I was able to save the multiple rows but the values are all the same, its the last data that i inputted so i guess i missed something?
Here are the codes:
Controller
public function addgrade()
{
$recordid = $this->input->post('recordid');
$studentid = $this->input->post('studentid');
$compid = $this->input->post('compid');
$subcompid = $this->input->post('subcompid');
$grade = $this->input->post('grade');
$classid = $this->input->post('classid');
foreach($this->UserModel->students() as $student):
if ($student->classid==$classid) { //$classid==33
$i=0;
$data = array(
'recordid' =>$recordid,
'studentid' => $studentid,
'compid' => $compid,
'subcompid' =>$subcompid,
'grade' =>$grade
);
$this->Crud->addgrade($data);
}
endforeach;
$this->session->set_flashdata('success', 'Successfully created!');
redirect('instructor');
}
Model
public function addgrade($data)
{
$this->db->insert('grade', $data);
}
View
<td>
<strong>
<input class="form-control inputScore" type="hidden" name="classid" value="<?php echo $classid;?>"></input>
<input class="form-control inputScore" type="hidden" name="recordid" value="<?php echo $record->id;?>"></input>
<input class="form-control inputScore" type="hidden" name="studentid" value="<?php echo $student->studentid;?>"></input>
<input class="form-control inputScore" type="hidden" name="compid" value="<?php echo $subcomp->id;?>"></input>
<input class="form-control inputScore" type="hidden" name="subcompid" value="<?php echo $subcomp->id;?>"></input>
<input class="form-control inputScore" type="text" name="grade"></input>
</strong></td>
All that gave me is this output on my database:
Did you try this instead? There's more detailed info about it here... Codeigniter - Append rows in view then add those rows to database table
$this->db->insert_batch('grade', $data);
In your form code, for all of your "name" variables such as name="classid", be sure to add "[]" at the end... name="classid[]"
Related
I am trying to update specific row in tables using select options tag .But it is updating last inserted row only and not the specificed.
I need solution.
controller:
public function user_status()
{
$this->load->model('customize_model');
$data = array("user_status" => $this->input->post('status'),
"user_id" => $this->input->post('user_id'));
$data1['user'] = $this->customize_model->update_status($data);
$this->load->view('custom/user',$data1);
}
Model:
public function update_status($data)
{
$user_id = $this->input->post('user_id');
$this->db->set($data);
$this->db->where('user_id',$user_id);
return $this->db->update('user',$data);
}
My View:
<?php
foreach($user->result() as $row)
{
?>
<tr>
<input type="hidden" class="form-control"
value="<?php echo $row->user_id; ?>"
name="user_id" />
<td><?php echo $row->user_id; ?></td>
<td><?php echo $row->user_status; ?></td>
<td>
<select class="form-control" name="status"
id="user_status">
<option value="Active">Active</option>
<option
value="Inactive">Inactive</option>
</select>
</td>
<td>
<button class="btn btn-primary" name="submit"
type="submit" value="<?php echo $row->user_id;?
>"> Update<?php echo $row->user_id;?></button>
</td>
</tr>
<?php
}
?>
The problem here is the same name="user_id" is looped in your view along with other name attributes. So the last value is sent to the controller.
In View:
Create two inputfields
<input type="hidden" name="global_userId" id="global_userId" />
<input type="hidden" name="global_status" id="global_status" />
Try setting the name and id as
name="status-<?php echo $row->user_id; ?>" id="status-<?php echo $row->user_id; ?>"
for all name attributes in loop.
and make the button type button rather than submit and make it call function onclick.
like
onClick="submitForm(<?php echo $row->user_id; ?>)"
and create the Jquery function to update the input field and submit the form:
function submitForm(userId){
$('#global_userId').val(userId);
var status = $('#status-'+userId).val();
$('#global_status').val(status);
$('#formId').submit();
}
In controller and model accept the 'global_userId' and 'global_status' for the values.
$user_id = $this->input->post('global_userId');
I made a page in php to get some data from mysql server using jquery post. The post method returns a json object. The json object contains a key named 'warning' if the record requested is already processed one. Else it contains several key value pairs from the requested record. But I am unable to check whether the json object contains a key called 'warning'. What is the problem with my code?
Given below is the form.
<form id="transitentry" name="transitentry" >
<fieldset>
<legend>Voucher Details</legend>
<label for "insert_id">Enter ID:</label><input type="text" id="insert_id" required/><br/>
<label for "voucher_type">Type of Voucher</label>
<select name="voucher_type" id="voucher_type" required>
<option class="green" value="">----Select Voucher Type----</option>
<option class="green" value="Invoice">Invoice</option>
<option class="green" value="Hand Receipt">Hand Receipt</option>
<option class="green" value="Manuscript Voucher">Manuscript Voucher</option>
</select>
<br/><br/>
<label for "invoice_no">Invoice No.:</label><input type="text" id="invoice_no"/><br/>
<label for "invoice_dt">Invoice/Receipt Date:</label><input type="text" id="datepicker" name="datepicker" value="<?php echo $dateindian; //echo date('d-m-Y'); ?>" /><input type="hidden" id="stddate" value="<?php echo $dateus; //echo date('d-m-Y'); ?>"/><br/>
<label for "item">Item/Description:</label><input class="item" type="text" id="item" size="100" required/><br/>
<label for "uom">Unit:</label><input type="text" id="uom" required/><br/>
<label for "qty">Qty:</label><input type="text" id="qty" required/><br/>
<label for "amount">Amount:</label><input type="text" id="amount" required/><br/>
<label for "supplier">Supplier</label><input type="text" id="supplier" required/><br/>
<label for "gst">GST :</label><input class="checkmark" type="checkbox" id="gst" value="Y"/><br/><br/>
<div align="center"><input id="frmsubmit" type="submit" value="Submit" /></div>
</fieldset>
</form>
Following jquery code is placed in the page to handle post
jQuery('#insert_id').change(function(){
var id=jQuery(this).val();
jQuery.post("scripts/get_imprest_transaction.php",{"insert_id":id},function(data){
if(data.hasKey("warning")){
alert(data.warning);
}else{
jQuery("#voucher_type").val(data.voucher_type);
jQuery("#invoice_no").val(data.bill_no);
jQuery("#datepicker").val(data.dateindian);
jQuery("#stddate").val(data.date);
jQuery("#item").val(data.iitem);
jQuery("#uom").val(data.uom);
jQuery("#qty").val(data.qty);
jQuery("#amount").val(data.amount);
jQuery("#supplier").val(data.supplier);
}
});
get_imprest_transaction.php which sends json object
require_once('../Connections/hari.php');
$insert_id=$_POST['insert_id'];
mysql_select_db($database_hari,$hari);
$sql= "SELECT * from imprest where transact_id=$insert_id";
$result=mysql_query($sql) or die(mysql_error());
$row=mysql_fetch_array($result);
if (mysql_num_rows($result)==0){
$return_data=array('msg'=>'Invalid ID or Data Not Entered');
header('Content-Type: application/json');
echo json_encode($return_data);
exit();
}else {
//$row=mysql_fetch_array($result);
if(is_null($row['submission_dt'])){
$warning='This transaction is already submitted for claim. If you change data , record in the database will differ from the hardcopy submitted to F&A';
$return_data=array( 'warning'=>$warning);
}else{
$dateindian= date('d-m-Y',strtotime($row['bill_dt']));
$item=$row['item'];
$date=$row['bill_dt'];
$uom=$row['uom'];
$qty=$row['qty'];
$amount=$row['amount'];
$bill_no=$row['bill_no'];
$gst=$row['gst'];
$voucher_type=$row['voucher_type'];
$supplier=$row['supplier'];
$return_data=array('iitem'=>$row['item'],'date'=>$row['bill_dt'], 'uom'=>$row['uom'], 'qty'=>$row['qty'], 'amount'=>$row['amount'], 'bill_no'=>$row['bill_no'], 'dateindian'=>$dateindian, 'gst'=>$row['gst'], 'voucher_type'=>$row['voucher_type'], 'supplier'=>$row['supplier']); }
header('Content-Type: application/json');
echo json_encode($return_data);
exit();
}
data is an object that represents the parsed JSON, returned by jQuery's post.
The problem is that there's no hasKey function that's defined as part of this object, so you can't call data.hasKey.
Now, assuming warning is a first-level property (and not a nested one), you can simply replace:
if (data.hasKey('warning'))
with:
if (data.warning !== undefined)
Is there a way that I can post two values at the same time from a single field in a table but hide one from the user?
I would like the following form to post the values ID and reason_name when it is submitted but have the user only be able to see (and edit in the text box) the reason_name.
<form name="add_positioning" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<table border="1" class="autoTable_pos">
<tr>
<td>Positioning</td><td> </td></tr>
<?
$sql= "SELECT * FROM gradeReason WHERE reason_userID = $user_id AND category = 'positioning' AND current = 1";
$result = mysqli_query($mysqli,$sql) or die(mysqli_error($mysqli));
while($row = mysqli_fetch_array($result)){?>
<tr>
<td>
<input type="text" name="reason[]" size="25" value="<? echo $row['reason_name']; ?>"/>
</td>
<td>
<input type="button" value="Delete" class="delRow_pos"/>
</td>
</tr>
<?
}
?>
<tr>
<td>
<input type="text" name="reason[]" size="25"/>
</td>
<td>
<input type="button" value="Delete" class="delRow_pos"/>
</td>
</tr>
<tr>
<td colspan="2" align="right">
<input type="submit" value="Save" name="save_reasons"/>
</td>
</tr>
</table>
</form>
The form POST action so far (basic echo at the moment for my own sanity to check that it posts the values correctly, which it does...)
if(isset($_POST['save_reasons'])) {
foreach($_POST['reason'] as $item) {
echo $item.'<br/>';
}
}
This table displays the values that are held in a database but enables the user to add more values by dynamically adding a new row (using JQUERY I haven't included) to the table when they type in an empty one at the bottom and also allows them to edit or delete existing values.
For each value posted I intend to check if the ID value is empty, if it is it means that it is a new value and enter a new record into the database, if it isn't update the existing record in the database with the corresponding ID. I don't have a problem writing that bit, I just can't think how to get the ID value posted as well as the reason_name while keeping ID hidden from the user.
Add the ID to the name attribute of the Text boxes of the reasons loaded from the DB. Leave the other Text boxes added using JQ without the ID.
E.g.
Text box which shows the existing reason loaded from the DB
<input type="text" name="reason[][ID]" size="25"/>
Text box added with JQ
<input type="text" name="reason[]" size="25"/>
Then once you submit the form you get you will get the following array.
array
'reason' =>
array
0 =>
array
14 => string 'VAL1' (length=4)
1 => string 'VAL2' (length=5)
By checking for an array in the each element in the "reason" array, you can differentiate two type of Text Boxes.
Here is the complete code I have tested.
<?PHP
//var_dump($_POST);
foreach($_POST['reason'] as $item=>$value)
{
if(is_array($value)){
foreach($value as $ID=>$reason)
{
echo "Existing Reason : ".$ID." - ".$reason."<br>";
}
}
else{
echo "New Reason : ".$item." - ".$value.'<br/>';
}
}
?>
<form action="" method="POST">
<input type="text" name="reason[][14]" size="25" value="aaaa"/>
<input type="text" name="reason[]" size="25" value="bbbbb"/>
<input name="" type="submit">
</form>
Assuming the id is at $row['reason_id'] I think you want:
$i = 0;
while($row = mysqli_fetch_array($result)){?>
<tr>
<td>
<input type="hidden" name="reason_id[<? echo $i; ?>]" size="25" value="<? echo $row['reason_id']; ?>"/>
<input type="text" name="reason[<? echo $i; ?>]" size="25" value="<? echo $row['reason_name']; ?>"/>
</td>
<td>
<input type="button" value="Delete" class="delRow_pos"/></td></tr>
<? $i++ } ?>
This way you can later
if(isset($_POST['save_reasons'])) {
foreach($_POST['reason'] as $key => $item) {
$id = $_POST['reason_id'][$key];
echo $id . " " . $item.'<br/>';
}
}
I want insert following data by insert_batch as in following example in database table (mysql):
HTML:
<input name="u_id[0][0]" value="76">
<input name="un[0][0]" value="1">
<input type="text" name="ue[0][0]" value="11">
<input type="text" name="up[0][0]" value="111">
<input name="u_id[1][0]" value="77">
<input name="un[1][1]" value="2">
<input type="text" name="ue[1][1]" value="22">
<input type="text" name="up[1][1]" value="222">
<input name="un[1][2]" value="3">
<input type="text" name="ue[1][2]" value="33">
<input type="text" name="up[1][2]" value="333">
PHP:
$u_id = $this->input->post('u_id');
$un = $this->input->post('un');
$up = $this->input->post('up');
$ue = $this->input->post('ue');
$data = array();
foreach ($un as $idx => $name) {
$data[] = array(
'u_id' => $u_id[$idx],
'un' => $un[$idx],
'up' => $up[$idx],
'ue' => $ue[$idx],
);
};
$this -> db -> insert_batch('units', $data);
I want insert they as this:
How should change php code and html code? what do i do?
I am assuming you are using CodeIgniter and that the name of the database table that you want to insert to is called 'units' and that its 'id' column is autoincrement.
I am basing off my solution from CodeIgniter User Guide Version 2.0.3 using a call to a helper ($this->db->insert_string()) of the Database class.
foreach ($data as $row)
{
$error_code = $this->db->insert_string('units', $row);
}
Refer to http://codeigniter.com/user_guide/database/helpers.html
The insert_string function that the Database class provides appears to take an associative array, build an INSERT statement from the elements inside, execute it and then return a numerical error code.
LOL, it's not pretty, but it might work sometimes:
<input name="u_id[]" value="76">
<input name="un[]" value="1">
<input type="text" name="ue[]" value="11">
<input type="text" name="up[]" value="111">
<input name="u_id[]" value="77">
<input name="un[]" value="2">
<input type="text" name="ue[]" value="22">
<input type="text" name="up[]" value="222">
<input name="un[]" value="3">
<input type="text" name="ue[]" value="33">
<input type="text" name="up[]" value="333">
$u_id=$this->input->post('u_id');
$un=$this->input->post('un');
$up=$this->input->post('up');
$ue=$this->input->post('ue');
for($i=0;$i<count($u_id);$i++){
for($ii=0;$ii<count($un[$i]);$ii++){
(count($un[$i])>1)?$unn=$un[$i][$ii+1]:$unn=$un[$i][$ii];
(count($ue[$i])>1)?$uen=$ue[$i][$ii+1]:$uen=$ue[$i][$ii];
(count($up[$i])>1)?$upn=$up[$i][$ii+1]:$upn=$up[$i][$ii];
$this->db->insert('units', array(//use db insert here
'u_id'=>$u_id[$i][0],
'un'=>$unn,
'ue'=>$uen,
'up'=>$upn,
));
}
}
I'd go so far as to suggest you not use it. But perhaps it might inspire someone to offer a better solution.
Cheers.
First let's explain what I want to do and then ask my question!
Well, I want to use a search filter for a query (the user should choose by which field will search the database, eg by name, code or fname) After the query runs, I want to show the data in some textfields, so the user can change them.
To do this, I put the first part (search filter-radio group- and filter value-text field-) in my first page(getStudentFilter.php). On submit, the query runs, I put values in SESSION and opens the second page(change_user.php) with my correct data!
If user change student's data, the update in db is ok, but in page change_user.php it shows the initial data again.
I tried to change SESSION values so I can keep my new values before run the update query, but it seems wrong.
Can someone give me a solution so I can fix the problem? Can this be done as it is or I have to change it and put both queries (select and update) in one form? Aaahh, I tried to put both in one form but I don't know how to control two "submit" in one form...
Thanks in advance..
my code after changes is
<form name="change_student" method="post" enctype="multipart/form-data" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" >
<?php
if ( isset($_POST['upd_student']) && $_POST['upd_student'] = 'Change' ){
echo "UPDATE";
//RUN UPDATE QUERY
}
elseif( isset($_POST['get_filter']) && $_POST['get_filter'] == 'Show' ){
echo "SELECT";
$query = "select * from student where ".$_POST['filter']."='".$_POST['filter_val']."'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$id = $row['idstudent'];
$fn = $row['fname'];
$ln = $row['lname'];
$ph = $row['phone'];
$sc = $row['school_dept'];
echo "<META HTTP-EQUIV='Refresh' CONTENT='0' >";
}
?>
<table width="310">
<tr><td><label><b>FILTER</b></label></td> </tr>
<tr><td><label><input type="radio" name="filter" value="idstudent" id="filter_5">ID </label></td></tr>
<tr><td><label><input type="radio" name="filter" value="fname" id="filter_3">FIRST NAME</label></td></tr>
<tr><td><label><input type="radio" name="filter" value="lname" id="filter_4">LAST NAME</label></td></tr>
<tr><td><input type="text" name="filter_val"> </td></tr>
<tr><td><input type="submit" name="get_filter" id="get_filter" value="Show"></td></tr>
</table>
<table>
<th colspan="2">STUDENT'S DATA</th>
<tr><td>ID</td><td><input type="text" name="st_id" value="<?php echo $id?>"></td></tr>
<tr><td>FIRST NAME</td><td><input type="text" name="fname" value="<?php echo $fn?>"></td></tr>
<tr><td>LAST NAME</td><td><input type="text" name="lname" value="<?php echo $ln?>"></td></tr>
<tr><td>PHONE</td><td><input type="text" name="phone" value="<?php echo $ph?>"></td></tr>
<tr><td>DEPT</td><td><input type="text" name="dept" value="<?php echo $sc?>"></td></tr>
</table>
<input type="submit" name="upd_student" value="Change">
</form>
Do not put search params into session.
Do not use 2 pages.
Make it all on one page and pass search parameters using GET method, like every search facility does.
To control 2 submits in one form you would have to test the values in you're php script .
Let's take the following html form:
<form action="index.php" name="contestForm" id="contestForm" method="POST">
<input type="submit" value="Select" name="select" />
<input type="submit" value="Update" name="update" />
</form>
Now in you're php script you would do this :
if ( isset($_POST['update']) && $_POST['update'] = 'Update' )
{
//do the update part
echo "UPDATE";
} elseif ( isset($_POST['select']) && $_POST['select'] == 'Select' )
{
//do the select part
echo "SELECT";
}