I want to ask about my php coding..
I'am doing some array coding but when I submit my data, in my database is will display an array at the 'description' and 'qty' column..
I use mysql..
Below is my array coding..
$item = array(
'item_description' => '',
'price' => '',
'qty' => '',
'amount' => '',
);
foreach ($item as $key => $value){
$item_description = $_POST['item_description'][$key];
$price = $_POST['price'][$key];
$qty = $_POST['qty'][$key];
$amount = $_POST['amount'][$key];}
}
This is my insert query.
$sql1="INSERT INTO payment_item (payment_id, payment_item_id, item_description, price, qty, amount)
VALUES
('$last_insert_payment_id','NULL','$_POST[item_description]','$_POST[price]','$_POST[qty]','$_POST[amount]')";
This is my form:
<form>
<h1>Payment Item</h1>
Payment ID :<input id="payment_id" name="payment_id" type="text"><br>
<input type="button" value="Add Row" onClick="addRow('tableID')"/>
<input type="button" value="Delete Row" onClick="deleteRow('tableID')"/>
<table class="table" bgcolor="#CCCCCC">
<thead>
<tr>
<td></td>
<td><center>Item Description</center></td>
<td><center>Price (RM)</center></td>
<td><center>Month</center></td>
<td><center>Amount (RM)</center></td>
</tr>
</thead>
<tbody id="tableID">
<tr>
<td><input type="checkbox" name="chk"></td>
<td>
<select name="item_description">
<option value="deposit">Deposit</option>
<option value="rental">Rental</option>
<option value="stamp">Stamp Duty</option>
<option value="process">Process Fee</option>
<option value="ap">AP</option>
</select>
</td>
<td><input id="price" name="price" type="text"></td>
<td><input id="month" name="qty" type="text"></td>
<td><input id="amount" name="amount" type="text"></td>
</tr>
</tbody>
</table>
<input name="submit" type="submit" value="Submit">
<input name="reset" type="reset" value="Reset">
</form>
I'am sorry for my poor english language..
But I really need any help from someone for this..
Thank you..
A word 'Array' appears when PHP is trying to cast an array as a string.
So for the field appeared as Array you have to process it somehow, depends on your application logic, converting whatever array you have to a proper string.
The question has nothing to do with mysql though.
Also remember that you have to format your SQL strings. At the very least do
$var = mysql_real_escape_string($var);
for the every variable you're putting into query, and wrap it single quotes in the query.
I don't know what your $_POST contains. But i assume you need this
<?php
$item = array(
'item_description' => '',
'price' => '',
'qty' => '',
'amount' => '',
);
foreach ($item as $key => &$value)
{
$value = $_POST[$key];
}
?>
EDIT:
You have to specify a form method
<form method="post">
and finally the INSERT query as
$sql1="INSERT INTO payment_item (payment_id, payment_item_id, item_description, price,qty, amount) VALUES ('$last_insert_payment_id','NULL','$item[item_description]','$item[price]','$item[qty]','$item[amount]')";
Related
I've done a ton of looking through older posts and no luck yet,
I'm trying to update multiple rows within a table from a single form with the ID being the primary key.
The contents are being displayed in what looks like a spreadsheet where the user can edit multiple rows.
I'm getting an undefined index: ID error.
The code I'm using bellow seems really close though something isn't right.
If anyones done this before and can correct this code your help would be greatly appreciated!
Thank you.
protected function updateMultiple(Request $request)
{
$data = $request->except(['_token']);
// dd($data);
for($i = 0; $i <= count($data['id']); $i++) {
$input = [
'id' => $data['id'][$i],
'Channel' => $data['Channel'][$i],
'Posts' => $data['Posts'][$i],
'Monthly_Admin_Fee' => $data['Monthly_Admin_Fee'][$i],
'Legal_Fee' => $data['Legal_Fee'][$i],
'Valuation_Fee' => $data['Valuation_Fee'][$i],
'Mortgage_Risk_Fee' => $data['Mortgage_Risk_Fee'][$i],
];
DB::table('membership')->update($input);
}
}
View
#foreach($members as $member)
<tr>
<td class="text-right">
<input type="text" style="padding-right: 8px;padding-left: 8px;" name="id[]" id="id">{{$member->id}}</td>
<td><input type="text" id="Channel" name="Channel[]" class="form-control" value="{{$member->Channel}}"></td>
<td><input type="text" id="Posts" name="Posts[]" class="form-control" value="{{$member->Posts}}"></td>
<td><input type="text" id="Monthly_Admin_Fee" name="Monthly_Admin_Fee[]" class="form-control" value="{{$member->Monthly_Admin_Fee}}"></td>
<td><input type="text" id="Legal_Fee" name="Legal_Fee[]" class="form-control" value="{{$member->Legal_Fee}}"></td>
<td><input type="text" id="Valuation_Fee" name="Valuation_Fee[]" class="form-control" value="{{$member->Valuation_Fee}}"></td>
<td><input type="text" id="Mortgage_Risk_Fee" name="Mortgage_Risk_Fee[]" class="form-control" value="{{$member->Mortgage_Risk_Fee}}"></td>
</tr>
#endforeach
This will do the job
view
#foreach($members as $member)
<tr>
<td class="text-right">
<input type="text" style="padding-right: 8px;padding-left: 8px;" name="id[{{$member->id}}]" id="id">{{$member->id}}</td>
<td><input type="text" id="Channel" name="Channel[{{$member->id}}]" class="form-control" value="{{$member->Channel}}"></td>
<td><input type="text" id="Posts" name="Posts[{{$member->id}}]" class="form-control" value="{{$member->Posts}}"></td>
<td><input type="text" id="Monthly_Admin_Fee" name="Monthly_Admin_Fee[{{$member->id}}]" class="form-control" value="{{$member->Monthly_Admin_Fee}}"></td>
<td><input type="text" id="Legal_Fee" name="Legal_Fee[{{$member->id}}]" class="form-control" value="{{$member->Legal_Fee}}"></td>
<td><input type="text" id="Valuation_Fee" name="Valuation_Fee[{{$member->id}}]" class="form-control" value="{{$member->Valuation_Fee}}"></td>
<td><input type="text" id="Mortgage_Risk_Fee" name="Mortgage_Risk_Fee[{{$member->id}}]" class="form-control" value="{{$member->Mortgage_Risk_Fee}}"></td>
</tr>
#endforeach
controller
foreach ($request->all() as $key => $data ) {
$input = [
'id' => $data['id'][$key],
'Channel' => $data['Channel'][$key],
'Posts' => $data['Posts'][$key],
'Monthly_Admin_Fee' => $data['Monthly_Admin_Fee'][$key],
'Legal_Fee' => $data['Legal_Fee'][$key],
'Valuation_Fee' => $data['Valuation_Fee'][$key],
'Mortgage_Risk_Fee' => $data['Mortgage_Risk_Fee'][$key],
];
DB::table('membership')->where('id',$key)->update($input);
}
that's your problem
for($i = 0; $i <= count($data['id']); $i++) {`
$data it's array of arrays, it doesn't have element with key 'id'
for($i = 0; $i <= count($data); $i++) {
or even better
foreach ($data as $row) {
$desired_keys = [
'Channel',
'Posts',
'Monthly_Admin_Fee',
'Legal_Fee',
'Valuation_Fee',
'Mortgage_Risk_Fee',
];
$input = array_only($row, $desired_keys);
BD::table('membership')->where('id', $row['id'])->update($input)
}
EDIT
Sorry, I've missled you. Because of your approach.
Can I suggest you this one?
#foreach($members as $i => $member)
<tr>
<td class="text-right">
<input type="text" style="padding-right: 8px;padding-left: 8px;" name="members[{{ $i }}][id]" id="id">{{$member->id}}
</td>
<td>
<input type="text" id="Channel" name="members[{{ $i }}][Channel]" class="form-control" value="{{$member->Channel}}">
</td>
<td>
<input type="text" id="Posts" name="members[{{ $i }}][Posts]" class="form-control" value="{{$member->Posts}}">
</td>
<td>
<input type="text" id="Monthly_Admin_Fee" name="members[{{ $i }}][Monthly_Admin_Fee]" class="form-control" value="{{$member->Monthly_Admin_Fee}}">
</td>
<td>
<input type="text" id="Legal_Fee" name="members[{{ $i }}][Legal_Fee]" class="form-control" value="{{$member->Legal_Fee}}">
</td>
<td>
<input type="text" id="Valuation_Fee" name="members[{{ $i }}][Valuation_Fee]" class="form-control" value="{{$member->Valuation_Fee}}">
</td>
<td>
<input type="text" id="Mortgage_Risk_Fee" name="members[{{ $i }}][Mortgage_Risk_Fee]" class="form-control" value="{{$member->Mortgage_Risk_Fee}}">
</td>
</tr>
#endforeach
Then in controller
protected function updateMultiple(Request $request)
{
foreach($request->get('members', []) as $member) {
DB::table('membership')->where('id', $member['id'])
->update(array_except($member, ['id']))
}
}
This approach is much more pretty, isn't it?
You cannot update multiple rows with different data with one query like the insert() method.
When the data is the same for all rows that need to be updated, you can use:
DB::table('membership')
->whereIn('id', [1,2,3,4])
->update(['Channel' => 'your-value', ..]);
Else you will need to use a foreach, if this takes to long take a look at Queing (https://laravel.com/docs/master/queues)
Mistake is in view. You have forgot to insert value to ID input.
<input type="text" style="padding-right: 8px;padding-left: 8px;" name="id[]" id="id" value="{{$member->id}}">{{$member->id}}</td>
you can follow like example :
$data_upate = array(
array(
'field1'=>'value1',
'field2'=>'value2',
...
),
array(
'field1'=>'value1',
'field2'=>'value2',
...
),
);
// list id of record you want to update//
$a_ids = array(....);
DB::table('table_name')->whereIn('id',$a_ids)->update($data_update);
Basically without knowing your data i would say remove [ID].
You dont need to know the ID. remove it from everywhere in this function,
EDIT
Just change your query to:
DB::table('membership')where(id, $data['id'][$i] )->update($input);
this will fetch the record with the current id and update it.
I have the following code which works well to get specific values and strip the strings like I need. However, I want to grab the fields with an int for the name and place those into an json array under my custom fields section. How can I iterate over the fields and find all fields with an int for the name then use that as the json ID with the passed value as the json value? IE:
input type="text" name="24349163" value="Here"
JSON encoded:
"id"=>'24349163', "value" =>'value of the field I need'
What I have now:
foreach($_POST as $key => $value){
if(preg_match('/^z_/i',$key)){
$arr[strip_tags($key)] = strip_tags($value);
}
}
$create = json_encode(array('ticket' => array('subject' => $arr['z_subject'],
'comment' => array( "body"=> $arr['z_description']), 'requester' =>
array('name' => $arr['z_name'], 'email' => $arr['z_requester']),
'custom_fields' => array("id"=>'24349163', "value" =>'Here'))));
Form for post:
<form id="zFormer" method="post" action="tickets.php" name="zFormer">
<table>
<tr>
<td valign="top">
<label for="z_name">Your Name:</label>
<input type="text" value="John Doe" name="z_name" />
</td>
<td valign="top">
<label for="z_requester">Your Email Address: </label>
<input type="text" value="john#domain.com" name="z_requester" />
</td>
</tr>
<tr>
<td valign="top">
<label for="z_subject">Title/Subject: </label>
<input type="text" value="Who needs a subject?" name="z_subject" />
</td>
<td valign="top">
<label for="z_description">Summary Description:</label>
<textarea name="z_description">Systems are down</textarea>
</td>
</tr>
<tr>
<td valign="top">
<label for="24275273">Incident Start Date:</label><br/>
<input type="date" name="24275273" value="" />
</td>
<td valign="top">
<label for="24275293">Incident Start Time:</label><br/>
<input type="time" name="24275293" value="" />
</td>
</tr>
I am not 100% sure I understand the question, but it sounds like you need to add an else in your foreach:
foreach($_POST as $key => $value){
if(preg_match('/^z_/i',$key)){
$arr[strip_tags($key)] = strip_tags($value);
}
elseif(is_numeric($key)) {
$arr['ticket']['custom_fields'] = array('id'=>$key,'value'=>$value);
/*
if you expect multiple id values:
$arr['ticket']['custom_fields'][] = array('id'=>$key,'value'=>$value);
*/
}
}
Your code is processing only $POST keys that start with z. To fix, use this.
foreach($_POST as $key => $value){
if(preg_match('/^z_/i',$key) || gettype($key) == 'integer'){
$arr[strip_tags($key)] = strip_tags($value);
}
}
I have added || gettype($key) == 'integer' to your if clause to process integer keys as well.
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/>';
}
}
After adding the extra field using javascript, the extra field values are not being sent by post method in php. Here in the code adding the basic 5 fields, rest are the extra fields that user can add if necessary
The code is as follows:
<script language="javascript">
var i = 11;
function changeIt()
{
my_div.innerHTML = my_div.innerHTML +"<tr><td> <input id='item"+i+"' name='item"+i+"' type='text' maxlength='255' value=''/></td><td><input id='kgorp"+i+"' name='kgorp"+i+"' type='text' maxlength='3' value=''/></td><br/></tr>";
i++;
}
</script>
<body>
Please enther the grocery items
<table>
<tr>
<th> Item name</th><th> kg/No of packet</th>
</tr>
<form method="post" action="gl.php">
<tr> <td><input id="item1" name="item1" type="text" maxlength="255" value=""/></td><td><input id="kgorp1" name="kgorp1" type="text" maxlength="3" value=""/></td></tr>
<tr> <td><input id="item2" name="item2" type="text" maxlength="255" value=""/></td><td><input id="kgorp2" name="kgorp2" type="text" maxlength="3" value=""/></td></tr>
<tr> <td> <input id="item3" name="item3" type="text" maxlength="255" value=""/></td><td><input id="kgorp3" name="kgorp3" type="text" maxlength="3" value=""/></td></tr>
<tr> <td> <input id="item4" name="item4" type="text" maxlength="255" value=""/></td><td><input id="kgorp4" name="kgorp4" type="text" maxlength="3" value=""/></td></tr>
<tr> <td> <input id="item5" name="item5" type="text" maxlength="255" value=""/></td><td><input id="kgorp5" name="kgorp5" type="text" maxlength="3" value=""/></td></tr>
<tr id="my_div"></tr>
<tr> <td><input id="saveForm" type="submit" value="Submit List" /></td><td><input id="addtxt" type="button" name="addtxt" value="Add more items" onClick="changeIt()" /></td> </tr>
</form>
</table>
</body>
The php code for retrieving the data sent via post method,
$i=1;
foreach ($_POST as $param_value) {
if ( empty( $param_value ) ) {
} else {
echo "<td>$param_value</td>";
if ( ( $i % 2 ) == 0 ) {
echo "</tr> <tr>";
}//echo $i;
}
$i++;
}
The problem is with how your form tag is placed and parsed in the HTML DOM.
Put the form tag higher in the document, after the tag.
<body>
Please enther the grocery items
<form method="post" action="gl.php">
and then change the javascript to this:
function changeIt()
{
var child = document.createElement('td');
child.innerHTML = "<input id='item"+i+"' name='item"+i+"' type='text' maxlength='255' value=''/><input id='kgorp"+i+"' name='kgorp"+i+"' type='text' maxlength='3' value=''/>";
document.getElementById("my_div").appendChild(child);
i++;
}
What you should get when you do a print_r($_POST) is:
Array ( [item1] => [kgorp1] => [item2] => [kgorp2] => [item3] => [kgorp3] => [item4] => [kgorp4] => [item5] => [kgorp5] => [item6] => [kgorp6] => [item7] => [kgorp7] => [item8] => [kgorp8] => [item9] => [kgorp9] => [item10] => [kgorp10] => [item11] => [kgorp11] => )
A better solution is to get rid of the table and tr/td tags and work with divs/spans for the form (its a lot nicer way to code, honestly :) )
Instead of using it in a function, simply put it inline inside your form in the following manner,
document.write('<input type="hidden" name="whatever" value="'+i+'">');
and make the adjustments necessary according to what you need.
for(i=0;i<=11;i++) {
document.getElementById("my_div").innerHTML = document.getElementById("my_div").innerHTML +"<tr>
<td> <input id='item"+i+"' name='item"+i+"' type='text' maxlength='255' value=''/></td>
<td><input id='kgorp"+i+"' name='kgorp"+i+"' type='text' maxlength='3' value=''/></td>
<br/>
</tr>";
}
Demo
I don't see where the my_div variable is initialized.
You could do, in the beginning of your changeIt function:
var my_div = document.getElementById('my_div')
Then another problem: don't name this variable my_div while it's actually a tr tag.
And further: in this tr tag, your changeIt function will include HTML containing another tr, so you'll end up with bad HTML. A suggestion: do not use tables but instead, div or li tags for such a listing.
How can I use foreach to insert multiple data in my database. I have a drop-down menu from my form that will be used to add and delete rows by js function. I would like to insert data from the new row (added in the form) into my database.
This is my form:
<form action="insert.php" method="POST">
<input type="button" value="Add Row" onClick="addRow('tableID')"/>
<input type="button" value="Delete Row"
onClick="deleteRow('tableID')"/>
<table class="table" bgcolor="#CCCCCC">
<thead>
<tr>
<td></td>
<td><center>Item Description</center></td>
<td><center>Price (RM)</center></td>
<td><center>Month</center></td>
<td><center>Amount (RM)</center></td>
</tr>
</thead>
<tbody id="tableID">
<tr>
<td><input type="checkbox" name="chk"></td>
<td>
<select name="item_description">
<option value="deposit">Deposit</option>
<option value="rental">Rental</option>
<option value="stamp">Stamp Duty</option>
<option value="process">Process Fee</option>
<option value="ap">AP</option>
</select>
</td>
<td><input id="price" name="price" type="text"></td>
<td><input id="month" name="qty" type="text"></td>
<td><input id="amount" name="amount" type="text"></td>
</tr>
</tbody>
</table>
</form>
This is my insert query:
<?php
//some connection code here
if(isset($_POST['submit']))
{
$item = array(
'item_description' => '',
'price' => '',
'qty' => '',
'amount' => '',
);
foreach ($item as $key => $value){
$value = $_POST[$key];
}
}
$last_insert_payment_id=mysql_insert_id();
$sql1="INSERT INTO payment_item (payment_id, payment_item_id, item_description, price, qty, amount)
VALUES
('$last_insert_payment_id','NULL','$_POST[item_description]','$_POST[price]','$_POST[qty]','$_POST[amount]')";
if (!mysql_query($sql1,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
?>
Hope someone can help me to figure this out. Thank you.
So you mean when you click 'Add row' and enter extra rows of data and then click 'Submit', only the last row gets inserted into the database?
I'm guessing that when you click 'Add Row', the following HTML is added to your table (same as the row in your question)
<tr>
<td><input type="checkbox" name="chk"></td>
... and so on
In this case, your $_POST['price'], $_POST['chk'] etc are probably getting overwritten for each row, because you now have multiple inputs with hane chk.
Try setting your input id="chk[]" instead of input id="chk", and then $_POST['chk'] will be an array, one for each row.
You could access each row via $_POST['chk'][i].
There are also the other recommendations in the comments about making your code safe to SQL injection, and the fact that $_POST[price] (like you have in your SQL statement) is invalid syntax; you probably want $_POST['price']. (Daedalus, Marc B, Los Frijoles).