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).
Related
How do I insert data from a form into multiple tables? This is what I have so far :
<?php
require 'db/connect.php';
$Apple = trim($_POST['Apple']);
$Orange = trim($_POST['Orange']);
$Banana = trim($_POST['Banana']);
if (empty($Apple) && empty($Orange) && empty($Banana)){
$error = "Please pick your fruits";
} else {
$insert = $db->prepare("INSERT INTO fruits (Apple, Orange, Banana) Values (?,?,?)");
$insert->bind_param("sss", $Apple, $Orange, $Banana);
?>
//HTML SECTION
<form action="" method="post">
<table>
<tr>
<td><label for="Apple">Apples :</label></td>
<td><input type="text" id="Apple" name="Apple"></td>
</tr>
<tr>
<td><label for="Orange">Oranges:</label></td>
<td><input type="text" id="Orange" name="Orange"></td>
</tr>
<tr>
<td><label for="Banana">Bananas:</label></td>
<td><input type="text" id="Banana" name="Banana"></td>
</tr>
<td>
<button type="submit" class="create" name="create">CREATE</button>
<a class="btn" href="index.php">BACK</a>
</td>
</tr>
</table>
What I would like to do is this - within the form, have another field (say tomatoes), that when the user clicks "submit", apple / orange / banana goes to the fruits table, and "tomato" goes to the "vegetables" table.
Does anyone know how to achieve this?
Here is what I finally came up with, I made the mistake of misplacing the binding code for "Tomato". One thing that I am still confused about, and am unsure about how to approach, is how I can make it to where when I click on a form field for the below example, it will populate a popup that shows current contents of the database, and allow you to copy contents of that popup(item) to the form field if needed. Another example would be a customers and products table, you make a form field to take a customer and a product, when you click on "product" form field, it populates with all products, and allows you to click on one of the populated products to assign to that customer.
<?php
require 'db/connect.php';
$Apple = trim($_POST['Apple']);
$Orange = trim($_POST['Orange']);
$Banana = trim($_POST['Banana']);
$Tomato= trim($_POST['Tomato']);
if (empty($Apple) && empty($Orange) && empty($Banana) && empty($Tomato)){
$error = "Please pick your fruits";
} else {
$insert = $db->prepare("INSERT INTO fruits (Apple, Orange, Banana) Values (?,?,?)");
$insert->bind_param("sss", $Apple, $Orange, $Banana);
$insert = $db->prepare("INSERT INTO veggies(Tomato) Values (?)");
$insert->bind_param("s", $Tomato);
?>
//HTML SECTION
<form action="" method="post">
<table>
<tr>
<td><label for="Apple">Apples :</label></td>
<td><input type="text" id="Apple" name="Apple"></td>
</tr>
<tr>
<td><label for="Orange">Oranges:</label></td>
<td><input type="text" id="Orange" name="Orange"></td>
</tr>
<tr>
<td><label for="Banana">Bananas:</label></td>
<td><input type="text" id="Banana" name="Banana"></td>
</tr>
<td>
<button type="submit" class="create" name="create">CREATE</button>
<a class="btn" href="index.php">BACK</a>
</td>
</tr>
</table>
I'm trying to develop a little project and I got a little problem
I'm making a PHP page connected to a MySQL Server. I have a page where only the administrator have access and that page allows him to change users information.
So, I have a select that show all usernames on website and 3 textbox where can be inserted the First Name, Last Name and e-mail.
My database update successfully, but what i'm trying to do is when is select a username on select the 3 textbook auto fill with that username information.
Here is an image that explains better what I would like to do.
Sorry for my english and thanks to all
http://s3.postimg.org/da9srvh5f/table_copy.jpg
<script type="text/javascript">
function reload() {
var val=document.getElementById("c-name").value;
self.location="your_url.php?name=" + val ;
//alert(val);
}
</script>
<form name="data" action="your_url.php" method="post">
<table id="tbl">
<tr>
<td>Name </td>
<td>
<select id="c-name" name="name" onChange="reload()" style="width:340px;">
<option value="">Select Name</option>
<option value="abc">ABC</option>
<option value="xyz">XYZ</option>
<option value="mno">MNO</option>
</select>
</td>
</tr>
<?php
if(isset($_GET['name'])){
$name = $_GET['name'];
$SQL_Data = "select * from client_data where cname = '".$name."'";
$result = mysqli_query($SQL_Data);
while($details = mysqli_fetch_array($result)) {
?>
<tr>
<td>First Name</td>
<td><input type="text" name="fname" class="c1" value="<?=$details['fname']?>" /></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" class="c7" name="lname" value="<?=$details['lname']?>" /></td>
</tr>
<tr>
<td>User Name</td>
<td><input type="text" class="c7" name="uname" value="<?=$details['uname']?>" /></td>
</tr>
<?php
} }
?>
<tr><td align="center" colspan="2"><input type="submit" name="submit" value="Submit" /></tr>
</table>
</form>
You could have your PHP backend return JSON data to your frontend. Then, with javascript, do something like:
document.getElementsById('ID').Value = VALUE;
Where ID is the Id of your select and VALUE is the value found in your JSON data.
Alternatively, you could do this purely in PHP/MySQL.
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 had following code.My textbox attend is looped for number of times.I want to get value of each attend when my form is post to insert value in database.
<form method="post" action="insert.php">
<label>Subject</label>
<input type="text" maxlength="30" name="subject" />
<label>Total Lectures</label>
<input type="text" maxlength="30" name="total" />
<table width="537" border="1">
<tr>
<td width="90">Name</td>
<td width="139">Roll Number </td>
<td width="136"> </td>
<td width="144">Attendence</td>
</tr>
<?php
$query=mysql_query("SELECT * FROM STUDENT");
$i=0;
while($rec=mysql_fetch_array($query)){
$i++;
?>
<tr>
<td><?php echo $rec['name']; ?></td>
<td><?php echo $rec['roll_number']; ?></td>
<td> </td>
<td><input type="text" maxlength="10" name="atten" /></td>
</tr>
<?php } ?>
</table>
<input type="submit" value="submit" />
</form>
and my insert.php page is
if($_SERVER['REQUEST_METHOD']=='POST'){
$query=mysql_query("SELECT * FROM STUDENT");
while($rec=mysql_fetch_array($query)){
$attend=$_POST['atten'];
$subject=$_POST['subject'];
$total=$_POST['total'];
$query1=mysql_query("INSERT INTO course VALUES('$i','$subject','$total','$attend','')") or die(mysql_error());
}
}
I am getting only 1 value of text box.
The problem is that you have many inputs all with the name atten. When you post this form, only one of those values will be carried forward.
If you change the name to atten[] all of the values would be posted as an array, which you would then have to loop through to build you insert query.
You could access this posted array as follows:
$attendee_array = $_POST['atten'];
foreach($attendee_array as $attendee) {
// perform insert or build insert query (prefereable as you can do all these inserts at once) here
// make sure to escape your data for input
}
Change the names of your inputs:
<input name="subject[]" value="Lorem" />
<input name="total[]" value="ipsum" />
<input name="atten[]" value="dolor" />
Then:
$_POST['subject'][0] == 'Lorem'
$_POST['total'][4] == 'amet'
If so, that would make my life ten times easier, as I could send an
indefinite amount of information through a form and get it processed
by the server simply by looping through the array of items with the
name "subject". etc.
You need to use input array like:
<input type="text" maxlength="10" name="attend[]" />
And then you will get all the values of attend in an array and you can loop through that $_POST['attend'].
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]')";