insert multiple rows to a table using foreach php - php

i need to insert multiple rows data into table
Date and inspection_id will remain same
but the input values are repeated.
Here is the script i have
<?php
if (isset($_POST["submit"])) {
$taskdate = date('Y:m:d');
$inspection_id = '1';
$post = $_POST['nfo'];
foreach ($post['point_id'] as $key => $value) {
$point_id.= $value.", ";
}
foreach ($post['point_comment'] as $key => $value) {
$point_comment.= $value.", ";
}
foreach ($post['point_value'] as $key => $value) {
$point_value.= $value.", ";
}
$query = "INSERT INTO `inspections` (`inspection_id`, `point_id`, `value`, `comment`)VALUES('$inspection_id', '$point_id', '$point_value', '$point_comment')";
$result = mysql_query($query);
HTML FORM i am USING
<form action="pentasks.php" method="post">
<select name="nfo[point_value][]">
<option selected>Chose</option>
<option value="1">Qualify</option>
<option value="2">Disqualify</option>
</select>
<input name = "nfo[point_comment][]" value = "" type="text">
<input type="hidden" name="inspection_id" value="<?= $task_id; ?>"> <!-- value From another query -->
<input type="hidden" name="nfo[point_id][]" value="<?= $spot_id3; ?>">
<input type="submit" name="submit" value="Submit">
</form>
Help please how i insert data
this is something in a table questions are defined
retrieved on form with input to answer

Try this
foreach ($post['point_comment'] as $key => $value) {
$point_comment=$post['point_comment'][$value];
$point_value= $post['point_value'][$value];
//run your query here
}
and mysql is depricated Learn mysqli_ function or PDO.
and change your select tag like this
<select name="point_value[]">
<select name="point_comment[]">

Arif thanks for your effort but your answer did not helped
spend few hours by ownself i got it working and here is the working solution for my question
HTML FORM
<input type = "text" name = "point_comment[]" />
<input type = "text" name = "point_value[]" />
Here is Foreach loop PHP
$my_comment = $_POST['point_comment'];
$point_comment = "";
foreach ($my_comment as $key => $value) {
$point_comment = $value;
$my_value = $_POST['point_value'];
$point_value = "";
foreach ($my_value as $key => $value) {
$point_value = $value;
// SQL INSERT or anything query here
} }
Hope this will help for those looking for similar

Related

How to write dynamic queries indepandant to the HTML form

I have problem with the following code i am trying t write the dynamic query which will be independent to my html form. Like i don't want to write the name a every single name of field in my query i want to make it dynamic thats why using the following the approach but the problem is right after the foreach block of code just below that
any other best way kindly guide me it'll be highly appreciated.
foreach(){
}
sql.="";
problem is here this sqli like contains only the last key and values not all the keys and values
Results:
INSERT INTO Patient(patient_cell) values (033480779)';
whereas i want results like this
INSERT INTO Patient(patient_name,patient_address,patient_pass,patient_cell) values (Saba,Daska,12345,033480779)';
HTML Form
<form method="post" action="Patient_data.php">
<label>Patient name:</label>
<input type="text" name="patient_name" placeholder="Patient name">
<br>
<label>Patient Address:</label>
<input type="text" name="patient_address" placeholder="Address">
<br>
<label>Patient's Password:</label>
<input type="text" name="patient_pass" placeholder="Password">
<br>
<label>Patient Cell:</label>
<input type="text" name="patient_cell" placeholder="Enter cell no.">
<br>
<input type="submit" value="Create Record" name="Create">
</form>
code:
$record['patient_name'] = $_POST['patient_name'];
$record['patient_address']=$_POST['patient_address'];
$record['patient_pass']=$_POST['patient_pass'];
$record['patient_cell']=$_POST['patient_cell'];
$dbname= new Db();
$dbname->Add($record);
function
public function Add($record) {
$var= $record;
$sql.= "INSERT INTO Patient";
foreach ($var as $key => $value) {
$key = "{$key},";
var_dump($key);
$value = "{$value},";
var_dump($value);
}
$sql.="(".substr($key,0,-1).") values (".substr($value,0,-1).")";
function Add($record) {
$var= $record;
$sql.= "INSERT INTO Patient ([%keys%]) values ([%vals%])";
$keys = "";
$vals = "";
foreach ($var as $key => $value) {
if (!empty($keys)) {
$keys .= ",";
}
$keys .= $key;
if (!empty($vals)) {
$vals .= ",";
}
$vals .= $value;
}
$sql = str_replace("[%keys%]", $keys, $sql);
$sql = str_replace("[%vals%]", $vals, $sql);
return $sql;
}
Try this function
Note : if some field is string you should add single quote in that field.

php how to build an array from a while loop and use data in a submit

I am building a simple cart with a while loop. I am showing product ID and Quantity. The user can change the quantity, and I want a single "UPDATE" button at the bottom of the cart that will update foreach of the items in the cart. It needs to pull the product ID and the new quantity entered by the user. How can I do this.
I can do it for a single cart item, but I can't figure out how to pass the multiple items as an array and treat the data once the UPDATE button is pressed.
My code:
<?
$data = mysql_query(.............);
if (isset($_POST['update']))
{
foreach ($array as $id => $qty)
{
$product_id = ...??..;
$new_qty = = ...??..;
$sql = "INSERT INTO.....".$product_id." and.... ".$new_qty."... ";
$insert = mysql_query($sql);
}
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post" >
<?
while ($data2 = mysql_fetch_array( $data)) { ?>
QTY: <input type="number" name="qty" class="form-field" value="<?=$data2['qty']?>" >
<input name="products_id" value="<?=$data2['product_id']?>" type="hidden">
<? } ?>
<input class="submit-button" type="submit" name="update" value="UPDATE QTY" />
</form>
You have to assign name attribute with square brackets to indicate array for your form elements.
Look here for explanation: here
Look here for simple concept example and alter it to suit your code: here
<?
while ($data2 = mysql_fetch_array( $data)) { ?>
QTY: <input type="number" name="qty[]" class="form-field" value="<?=$data2['qty']?>" >
<input name="products_id[]" value="<?=$data2['product_id']?>" type="hidden">
<? } ?>
then
if (isset($_POST['update']))
{
$array = $_POST['products_id'];
$quantities = $_POST['qty'];
foreach ($array as $key => $id)
{
$product_id = $id;
$new_qty = = $quantities[$key];
$sql = "INSERT INTO.....".$product_id." and.... ".$new_qty."... ";
$insert = mysql_query($sql);
}
}

Getting checked checkbox values in variable PHP

I have added two checkboxes on page with submit button. After submitting there is a method having foreach loop to check which checkbox is checked , and that checkbox value should get in variable. If both checkbox's are checked then it should append both values in variable. But in my case the values are repeating. And also if i check both checkboxes it is picking up only second checkbox value.
Below is my code for HTML :
<form name="" action="" method="post">
<input type="checkbox" name="checkbox[]" value="Training"/> Training <br/><br/>
<input type="checkbox" name="checkbox[]" value="Posting"/> Posting<br/><br/>
<input type="submit" value="Submit"/>
</form>
Code for PHP:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$value = "";
$name = $_POST['checkbox'];
// optional
// echo "You chose the following color(s): <br>";
foreach ($name as $value){
//echo $value.", ";
$value .= $value;
}
echo $value;
//print "<script>alert('".$value."')</script>";
}
?>
$value is a local variable to the loop it get overwritten when the loop continues again.
$result = '';
foreach ($name as $value){
$result .= $value;
}
echo $result;
$name = (array)$_POST['checkbox'];
$value = '';
foreach ($name as $val){
$value .= $val;
}

why does my code echo my post variables but still give me Invalid argument supplied for foreach() warnings?

I get two warnings Warning: Invalid argument supplied for foreach() but I still retrieve my expected post variables. Where am I going wrong? It says the warning is in regard to line 7, which in this case is the line that begins; foreach($value as $k => $v)
<!------------- quote.php ----------------->
<body>
What services are you interested in? <br/><br/>
<form name="input" action="quote2.php" method="post">
<?php
$services = array('Tree Felling', 'Height Reduction', 'Crown Thinning', 'Deadwooding/Ivy Removal', 'Stump Grinding', 'Other');
foreach ($services as $option) { ?>
<input id="<?= $option ?>" type="checkbox" name="services[]" value="<?= $option ?>" />
<label for="<?= $option ?>"><?= $option ?></label>
<br />
<? }
?>
<br/>
<input name="name" type="text" />NAME</br>
<input name="place" type="text"/>TOWN</br/>
<input type="submit" value="Submit">
</form>
</body>
<!------------ quote2.php -------------->
<?php
echo '<h3>SERVICES REQUIRED</h3>';
foreach ($_POST as $key => $value) {
foreach($value as $k => $v)
{
echo '<p>'.$v.'</p>';
}
}
echo "<hr /><h3>DETAILS</h3>";
echo $name = $_POST['name'];
echo "</br>";
echo $place = $_POST['place'];
echo "<hr/>"
?>
A number of the form controls do not have names that end in [] and so are not arrays.
You can't loop over a string.
You should pull out each value of the submitted data individually and only loop over services.
The problem is that there is a very real possibility that not all of the items in your $_POST array will have values of type array; which you are assuming according to the code in quote2.php
A simple is_array() check will ensure that only arrays get iterated over in the foreach, here is the edited file contents:
<!------------ quote2.php -------------->
<?php
echo '<h3>SERVICES REQUIRED</h3>';
foreach ($_POST as $key => $value) {
if (is_array($value)) {
foreach($value as $k => $v)
{
echo '<p>'.$v.'</p>';
}
}
}
echo "<hr /><h3>DETAILS</h3>";
echo $name = $_POST['name'];
echo "</br>";
echo $place = $_POST['place'];
echo "<hr/>"
?>
That should do the trick.
Try wrapping your foreach loop in an if statement to check the array is an array. For example:
if (is_array($services)) {
foreach ($services as $option) {
// Some code
}
}
Although I wouldn't worry too much. This is just a cleaner way of writing your code.

PHP: How to correctly loop through multi-dimen post arrays

If I have a form with fields like this.
THERE WILL BE MULTIPLE ROWS OF THESE FIELDS HENCE THE SQUARE BRACKETS
<input type="text" name="txt-receipt-number[]" value="" />
<input type="text" name="txt-stock-number[]" value="" />
<input type="text" name="txt-repair-code[]" value="" />
How do I loop through the $_POST variable to get the values because its getting the field names but not the values, what am I doing wrong please?
$fields = array();
$values = array();
foreach($_POST as $field => $value) {
$fields[] = $field;
echo $value;
}
Output:
ArrayArrayArrayArrayArrayArrayArrayArrayArray
Update:
Sorry, quick edit for correct output...
Further Update:
Lets ignore the insert, how do I get the values please?
Remove the [] of your text input, or you will get $value of array type.
<input type="text" name="txt-receipt-number" value="" />
<input type="text" name="txt-stock-number" value="" />
<input type="text" name="txt-repair-code" value="" />
And don't forget to quote your values.
foreach($_POST as $field => $value)
{
if(is_array($value))
{
foreach($value as $k => $val)
{
echo $val;
}
}
else
{
echo $value;
}
}
Works for regular fields and one-dimensional _POST fields.
You will have some other problems though, with column names like sales_receipt-number, etc. You should enclose those in backquotes, and you must also escape them since they are going directly into your SQL statement. They are just as vulnerable to SQL injection as the VALUES().
$fields[] = "`" . mysql_real_escape_string($field) . "`";
Update 2
To get the values and do the insert in a loop, the SQL needs to be reconstructed each time in the loop, using one set of array values.
// Find the number of loops necessary
// Unless all fields are always required, this will need to be the $_POST key with the most values
$numLoops = count($_POST['txt-receipt-number']);
fields = array();
$values = array();
for ($i = 0; $i < count($_POST); $i++) {
foreach($_POST as $field => $value) {
$fields[] = "`" . mysql_real_escape_string($field) . "`";
$values[] = mysql_real_escape_string($_POST[$field][$i]);
// Now build the SQL for this loop iteration.
$sql = 'insert into table(' . join(',', $fields) . ') values(' . join(',', $values) . ')';
}
}
To be honest, I see many problems in this code...
Using foreach to build dynamic list of fields that need to be inserted. Don't you have, for example, anything like <input type='submit' name='add_data'/>? It's common to have submit buttons, and, with your code, you would try to edit DB table's field named add_data. This is also unsafe, as it (a) reveals table structure and (b) gives possibility to make SQL errors by manually changing field names, which may lead to another security/stability issues.
Lack of escaping field names. May lead to SQL injections.
Using - sign in field names. insert into table(sales_receipt-number, ... just won't work.
As for handling posted arrays...
<form method='post' action=''>
<table border='1'>
<tr>
<td><input type='text' name='receipt_number[]'/></td>
<td><input type='text' name='stock_number[]'/></td>
<td><input type='text' name='repair_code[]'/></td>
</tr>
<tr>
<td><input type='text' name='receipt_number[]'/></td>
<td><input type='text' name='stock_number[]'/></td>
<td><input type='text' name='repair_code[]'/></td>
</tr>
<tr>
<td><input type='text' name='receipt_number[]'/></td>
<td><input type='text' name='stock_number[]'/></td>
<td><input type='text' name='repair_code[]'/></td>
</tr>
<tr>
<td colspan='3'>
<input type='submit' name='add_items'/>
</td>
</tr>
</table>
</form>
<pre>
<?php
function handleAddingItem() {
if ( !isset($_POST['receipt_number'], $_POST['stock_number'], $_POST['repair_code']) ) {
trigger_error("Some field is undefined");
return false;
}
if ( !is_array($_POST['receipt_number']) || !is_array($_POST['stock_number']) || !is_array($_POST['repair_code']) ) {
trigger_error("Some field is not an array");
return false;
}
$keys = array_keys($_POST['receipt_number']);
if ( array_keys($_POST['stock_number']) !== $keys || array_keys($_POST['repair_code']) !== $keys ) {
trigger_error("Posted arrays have different keys");
return false;
}
foreach ( $keys as $key ) {
if ( empty($_POST['receipt_number'][$key]) && empty($_POST['stock_number'][$key]) && empty($_POST['repair_code'][$key]) ) {
continue;
}
$receiptNumber = mysql_real_escape_string($_POST['receipt_number'][$key]);
$stockNumber = mysql_real_escape_string($_POST['stock_number'][$key]);
$repairCode = mysql_real_escape_string($_POST['repair_code'][$key]);
$sql = "
insert into table_name set
receipt_number = '{$receiptNumber}',
stock_number = '{$stockNumber}',
repair_code = '{$repairCode}'
";
echo $sql;
}
return true;
}
function handlePost() {
print_r($_POST);
if ( isset($_POST['add_items']) ) {
handleAddingItem();
}
}
if ( $_SERVER['REQUEST_METHOD'] === 'POST' ) {
handlePost();
}
?>
Output:
Array
(
[receipt_number] => Array
(
[0] => 123
[1] =>
[2] =>
)
[stock_number] => Array
(
[0] =>
[1] =>
[2] =>
)
[repair_code] => Array
(
[0] =>
[1] =>
[2] =>
)
[add_items] => Submit Query
)
insert into table_name set
receipt_number = '123',
stock_number = '',
repair_code = ''
Common practice might be to pass additional field - row's ID. If it has a value, then action is "edit", if it is empty, action is "create".
This is a little bit strange but try it :
<?php
foreach($_POST['txt-receipt-number'] as $k=>$v){
$array[$k]['txt-receipt-number'] = $_POST['txt-receipt-number'][$k];
$array[$k]['txt-stock-number'] = $_POST['txt-stock-number'][$k];
$array[$k]['txt-repair-code'] = $_POST['txt-repair-code'][$k];
}
$fields = array();
$values = array();
foreach($array as $row) {
foreach($row as $field => $value) {
$values[] = $value;
$fields[] = $field;
}
}
var_dump($fields);
var_dump($values);
?>
<form method='post' action=''>
<input type="text" name="txt-receipt-number[]" value="" /><br>
<input type="text" name="txt-stock-number[]" value="" /><br>
<input type="text" name="txt-repair-code[]" value="" /><br>
----
<input type="text" name="txt-receipt-number[]" value="" /><br>
<input type="text" name="txt-stock-number[]" value="" /><br>
<input type="text" name="txt-repair-code[]" value="" /><br>
<input type="submit" value="go">
</form>

Categories