PHP MySQL insert/update multiple rows at once [duplicate] - php

This question already has an answer here:
Post form and update multiple rows with mysql
(1 answer)
Closed last year.
I have read this question: https://stackoverflow.com/questions/20255690/php-insert-a-variable-number-of-records-to-mysql-from-a-html-form#=
But I cannot figure out how to apply this to a form with multiple inputs.
I want these inputs to go into the same row (per array id).
My PHP renders the following HTML:
<div class="panel-body">
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-4 col-lg-3 employee-container">
<label for="visible-107">
<img title="Jane Doe" src="/images/prof-pics/default.jpg" class="img-responsive img-circle" alt="Jane Doe">
</label>
<h4><input type="checkbox" name="visible[0]" id="visible-107"> <label for="visible-107">Jane Doe</label></h4>
<div class="input-group">
<span class="input-group-addon">Function</span>
<input type="text" class="form-control" name="function[0]" id="function-107">
</div>
<div class="input-group">
<span class="input-group-addon">Order</span>
<select class="form-control" name="order[0]" id="order-107">
<option value="">-- select one --</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
Description<br>
<textarea class="form-control" name="description[0]" id="description-107"></textarea>
</div>
<div class="col-xs-12 col-sm-6 col-md-4 col-lg-3 employee-container">
<label for="visible-2"><img title="John Doe" src="/images/prof-pics/default.jpg" class="img-responsive img-circle" alt="John Doe"></label>
<h4><input type="checkbox" name="visible[1]" id="visible-2"> <label for="visible-2">John Doe</label></h4>
<div class="input-group">
<span class="input-group-addon">Function</span>
<input type="text" class="form-control" name="function[1]" id="function-2">
</div>
<div class="input-group">
<span class="input-group-addon">Order</span>
<select class="form-control" name="order[1]" id="order-2">
<option value="">-- select one --</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
Description<br>
<textarea class="form-control" name="description[1]" id="description-2"></textarea>
</div>
</div>
</div>
How would I iterate these arrays so that I can insert/update them as a row per array ID?
After implementing Nana Partykar's answer
function set_team($web_mysqli, $mysqli, $uid, $visible, $function, $order, $description, $action, $update_id = null ) {
$number_empl = sizeof($function);
for($i=0; $i<$number_empl; $i++) {
$uid = $uid[$i];
$visible = $visible[$i];
$function = $function[$i];
$order = $order[$i];
$description = $description[$i];
$name = get_full_name($mysqli, $uid, false);
$sql = "INSERT INTO team (name, function, description, displayorder, visible) VALUES ('$name', '$function', '$description', '$order', '$visible')";
$web_mysqli->query($sql) or die(mysqli_error($web_mysqli));
}
$_SESSION['success'] = "Employee list website updated";
header("Location: ".BASE_PATH."/includes/views/list-employees.php");
exit();
if(isset($_POST['submit-btn'])) {
set_team($web_mysqli, $mysqli, $_POST['uid'], $_POST['visible'], $_POST['function'], $_POST['order'], $_POST['description'], 'insert');
}
When I save only the first name is inserted into the table followed by 3 blank rows.

No Need for name[0],
<input type="checkbox" name="visible[0]" id="visible-107">
<input type="text" class="form-control" name="function[0]" id="function-107">
<select class="form-control" name="order[0]" id="order-107">
<textarea class="form-control" name="description[0]" id="description-107"></textarea>
Make
<input type="checkbox" name="visible[]" id="visible-107">
<input type="text" class="form-control" name="function[]" id="function-107">
<select class="form-control" name="order[]" id="order-107">
<textarea class="form-control" name="description[]" id="description-107"></textarea>
SomePage.php (Submit Page)
<?
extract($_POST);
$sizeOfFunc=sizeof($function);
for($i=0;$i<$sizeOfFunc;$i++)
{
$Visible=$visible[$i];
$Function=$function[$i];
$Order=$order[$i];
$Description=$description[$i];
echo $Visible." ".$Function." ".$Order." ".$Description;
//Use $Visible, $Function, $Order, $Description in your query
}
?>
Updated Code
Don't use same variable name. Atleast change variable name.
This is wrong.
$uid = $uid[$i];
$visible = $visible[$i];
$function = $function[$i];
$order = $order[$i];
$description = $description[$i];
This is correct
$Uid = $uid[$i];
$Visible = $visible[$i];
$Function = $function[$i];
$Order = $order[$i];
$Description = $description[$i];
I've changed your code. Use the below code. It will work.
<?
function set_team($web_mysqli, $mysqli, $uid, $visible, $function, $order, $description, $action, $update_id = null ) {
$number_empl = sizeof($function);
for($i=0; $i<$number_empl; $i++) {
$Uid = $uid[$i];
$Visible = $visible[$i];
$Function = $function[$i];
$Order = $order[$i];
$Description = $description[$i];
$name = get_full_name($mysqli, $Uid, false);
$sql = "INSERT INTO team (name, function, description, displayorder, visible) VALUES ('$name', '$Function', '$Description', '$Order', '$Visible')";
$web_mysqli->query($sql) or die(mysqli_error($web_mysqli));
}
$_SESSION['success'] = "Employee list website updated";
header("Location: ".BASE_PATH."/includes/views/list-employees.php");
exit();
if(isset($_POST['submit-btn'])) {
set_team($web_mysqli, $mysqli, $_POST['uid'], $_POST['visible'], $_POST['function'], $_POST['order'], $_POST['description'], 'insert');
}
?>
I checked your code in my system after editing. It working fine.
<?
error_reporting(0);
extract($_POST);
echo $number_empl = sizeof($function);
for($i=0; $i<$number_empl; $i++)
{
$Visible = $visible[$i];
$Function = $function[$i];
$Order = $order[$i];
$Description = $description[$i];
$name="Just";
echo $sql = "INSERT INTO team (name, function, description, displayorder, visible) VALUES ('$name', '$Function', '$Description', '$Order', '$Visible')"."<br>";
}
?>

Related

How to Save select option value data instead of Id using PHP MYSQL

How best can I save a select option value name instead of the id using just Ajax, PHP and MYSQL.
I tried many ways but for now when I select the data and store back it keeps saving generated id and that's not what I want.
When i decided to change the id of the selection option to value i the values does show on the drop down.
Details.php
<form method="post" name="signup" onSubmit="return valid();">
<label class="control-label">Profile ID</label>
<select id="employee" name="regcode" class="form-control">
<option value="" selected="selected">Select Profile ID</option>
<?php
$sql = "SELECT id,regcode FROM tbstudentprofile";
$query = $dbh->prepare($sql);
$query->execute();
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
?>
<option name="regcode" value="<?php echo $row["id"]; ?>">
<?php echo $row["regcode"]; ?> </option>
<?php } ?>
</select>
<div class=" form-group1 form-last>
<label class=" control-label">Status</label>
<textarea name="status" row="2"></textarea>
</div>
<button type="submit" name="save">Save </button>
</form>
enter code here
query
if (isset($_POST['save'])) {
$regcode = $_POST['regcode'];
$status = $_POST['status'];
$sql = "INSERT INTO studentschooltbl(regcode,status) VALUES(:regcode,:status)";
$query = $dbh->prepare($sql);
$query->bindParam(':regcode', $regcode, PDO::PARAM_STR);
$query->bindParam(':status', $status, PDO::PARAM_STR);
$query->execute();
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$lastInsertId = $dbh->lastInsertId();
if ($lastInsertId) {
$msg = " Registration successfully";
} else {
$error = "error";
}
}

Inserting Data into MySQL table using HTML form

I am currently trying to insert rows into a MySQL database, and most of the code is there but I'm having a few issues I can't diagnose. I know the database connection is good, and every time the submit button is pressed it runs the correct php script. The issue I'm having is that it always adds 2 records to the database table and fails to carry though any of the form data (it inserts two completely blank rows.)
Here's the code for the form (with a little extra code for the wordpress page)
<div class="main-container">
<div class="content-area">
<div class="middle-align">
<div class="site-main" id="sitefull">
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', 'page' ); ?>
<div>
<form method="POST" name="cutting tool" action="add-tool-script.php">
<table style="width:auto;">
<tr>
<th width="50%"><h2><ul>Tool Information</ul></h2><br></th>
<th width="50%"><ul><h2>Storage Information</h2></ul><br></th>
</tr>
<tr>
<td width="50%">
<h3>Tooling Name</h3><br>
<input type="text" name="name" placeholder="e.g. ShearHog"><br><br>
<h3>Tooling Type</h3><br>
<select name="type">
<option selected disabled hidden style='display: none' value=''></option>
<option value="Ballnose Endmill">Ballnose Endmill</option>
<option value="Bullnose Endmill">Bullnose Endmill</option>
<option value="Boring Bar">Boring Bar</option>
<option value="Brush">Brush</option>
<option value="Burnishing">Burnishing</option>
<option value="Chamfer Mill">Chamfer Mill</option>
<option value="Countersink">Countersink</option>
<option value="Drill">Drill</option>
<option value="Drill/Mill">Drill/Mill</option>
<option value="Engraver">Engraver</option>
<option value="Face Mill">Face Mill</option>
<option value="Flat Endmill">Flat Endmill</option>
<option value="High Feed Mill">High Feed Mill</option>
<option value="Reamer">Reamer</option>
<option value="Slitting Saw">Slitting Saw</option>
<option value="Spot Drill">Spot Drill</option>
<option value="Tap">Tap</option>
<option value="Threadmill">Threadmill</option>
<option value="Woodruff">Woodruff</option>
<option value="Other">Other</option>
</select><br><br>
<h3>Tooling Brand</h3><br>
<input type="text" name="brand" placeholder="e.g. Lakeshore Carbide"><br><br>
<h3>Part Number</h3><br>
<input type="text" name="part_number" placeholder="e.g. 360014X"><br><br>
<h3>Price</h3><br>
<input type="text" name="price" placeholder="e.g. 24.95"><br><br>
<h3>Overall Length</h3><br>
<input type="text" name="oal" placeholder="e.g. 2.5"><br><br>
<h3>Tooling Material</h3><br>
<select name="material">
<option selected disabled hidden style='display: none' value=''></option>
<option value="Carbide">Carbide</option>
<option value="Ceramic">Ceramic</option>
<option value="Diamond">Diamond</option>
<option value="HSS">HSS</option>
<option value="Powdered Metal">Powdered Metal</option>
</select><br><br>
<h3>Cutting Diameter</h3><br>
<input type="text" name="cutting_diam" placeholder="e.g. 0.250"><br><br>
<h3>Shank Diameter</h3><br>
<input type="text" name="shank_diam" placeholder="e.g. .250"><br><br>
<h3>Number of Flutes</h3><br>
<input type="text" name="flutes" placeholder="e.g. 3"><br><br>
<h3>Length of Cut (Flute Length)</h3><br>
<input type="text" name="loc" placeholder="e.g. .750"><br><br>
<h3>Corner Radius</h3><br>
<input type="text" name="corner_rad" placeholder="e.g. .004"><br><br>
</td>
<td width="50%">
<h3>Quantity in Stock</h3><br>
<input type="text" name="qty" placeholder="e.g. 37"><br><br>
<h3>Minimum Trigger Quantity</h3><br>
<input type="text" name="trigger_qty" placeholder="e.g. 4"><br><br>
<h3>Reorder Link</h3><br>
<input type="text" name="reorder_link" placeholder="e.g. example.com"><br><br>
<h3>Toolbox Number</h3><br>
<input type="text" name="toolbox_no" placeholder="e.g. 1"><br><br>
<h3>Drawer Number</h3><br>
<input type="text" name="drawer_no" placeholder="e.g. 1"><br><br>
<h3>Bin Number</h3><br>
<input type="text" name="bin_no" placeholder="e.g. 1"><br><br>
<h3>Product</h3><br>
<input type="text" name="product" placeholder="e.g. Widget #2"><br><br>
<input type="submit" value="Add to Tool Crib" name="submitbutton" action="submit"/>
</td>
</tr>
</table>
</form>
</div>
<?php
//If comments are open or we have at least one comment, load up the comment template
if ( comments_open() || '0' != get_comments_number() )
comments_template();
?>
<?php endwhile; // end of the loop. ?>
</div>
<div class="clear"></div>
</div>
</div>
</div>
<?php get_footer(); ?>
And here's the code for the php script to add form data to the database:
//MySQL Database
$servername = "url.com";
$username = "user_login";
$password = "user_password";
$datab = "database_name";
// Create connection
$conn = new mysqli($servername, $username, $password, $datab);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$name = $_REQUEST['name'];
$type = $_REQUEST['type'];
$brand = $_REQUEST['brand'];
$part_number = $_REQUEST['part_number'];
$price = $_REQUEST['price'];
$oal = $_REQUEST['oal'];
$material = $_REQUEST['material'];
$cutting_diam = $_REQUEST['cutting_diam'];
$shank_diam = $_REQUEST['shank_diam'];
$flutes = $_REQUEST['flutes'];
$loc = $_REQUEST['loc'];
$corner_rad = $_REQUEST['corner_rad'];
$qty = $_REQUEST['qty'];
$trigger_qty = $_REQUEST['trigger_qty'];
$reorder_link = $_REQUEST['reorder_link'];
$toolbox_no = $_REQUEST['toolbox_no'];
$drawer_no = $_REQUEST['drawer_no'];
$bin_no = $_REQUEST['bin_no'];
$product = $_REQUEST['product'];
$username = $user_login;
$sql = "INSERT INTO `cutting tools` (`name`, `type`, `brand`, `part_number`, `reorder_link`, `oal`, `price`, `material`, `cutting_diam`, `shank_diam`, `flutes`, `loc`, `corner_rad`, `qty`, `trigger_qty`, `user`, `drawer_no`, `bin_no`, `toolbox_no`)
VALUES ('$name', '$type', '$brand', '$part_number', '$reorder_link', '$oal', '$price', '$material', '$cutting_diam', '$shank_diam', '$flutes', '$loc', '$corner_rad', '$qty', '$trigger_qty', '$username', '$drawer_no', '$bin_no', '$toolbox_no')";
if(mysqli_query($conn, $sql)){
echo "Record added successfully.";
} else{
echo "ERROR: Could not execute $sql. " . mysqli_error($conn);
}
// Close connection
mysqli_close($conn);
?>
Also I know my database is vulnerable to injection, that was a change I planned on making once the form was up and running.
Use WordPress to your advantage. Instead of defining your own connection, use global $wpdb, and then use the insert command.
global $wpdb;
$success = $wpdb->insert('tbl_name', array(<br>
'field1_name' => $_REQUEST['field1'],<br>
'field2_name' => $_REQUEST['field2'],<br>
));<br>
if($success){<br>
echo "Inserted correctly";<br>
} else {<br>
echo "Something went awry!";<br>
}
Here's a prepared statement, a more secure way of creating a MYSQL record in your table.
<?php
//MySQL Database
$servername = "url.com";
$username = "user_login";
$password = "user_password";
$datab = "database_name";
// Create connection
$con = new mysqli($servername, $username, $password, $datab);
global $con;
// Post form data
$name = $_POST['name'];
$type = $_POST['type'];
$brand = $_POST['brand'];
$part_number = $_POST['part_number'];
$price = $_POST['price'];
$oal = $_POST['oal'];
$material = $_POST['material'];
$cutting_diam = $_POST['cutting_diam'];
$shank_diam = $_POST['shank_diam'];
$flutes = $_POST['flutes'];
$loc = $_POST['loc'];
$corner_rad = $_POST['corner_rad'];
$qty = $_POST['qty'];
$trigger_qty = $_POST['trigger_qty'];
$reorder_link = $_POST['reorder_link'];
$toolbox_no = $_POST['toolbox_no'];
$drawer_no = $_POST['drawer_no'];
$bin_no = $_POST['bin_no'];
$product = $_POST['product'];
// Prepared statement
$insert = mysqli_prepare($con, "insert into cutting tools (name,type,brand,part_number,reorder_link,oal,price,material,cutting_diam,shank_diam,flutes,loc,corner_rad,qty,trigger_qty,user,drawer_no,bin_no,toolbox_no) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
mysqli_stmt_bind_param($insert, "sssssssssssssssssss", $name,$type,$brand,$part_number,$reorder_link,$oal,$price,$material,$cutting_diam,$shank_diam,$flutes,$loc,$corner_rad,$qty,$trigger_qty,$product,$drawer_no,$bin_no,$toolbox_no);
mysqli_stmt_execute($insert);
if ($insert) { echo "success"; mysqli_close($con); } else { echo "error"; mysqli_close($con); }
?>
Pay close attention to the order of your columns and the data you are submitting to those columns. I have edited this post because your order was incorrect in several places.
The column names and the data variables being uploaded to them have to be in the exact same order if you want data created correctly.
By the way the variable $product does not seem to match the column name of user, you may want to check this.

get option values from database codeigniter

I have a php form where I want to select options for a field Email from a list of values saved in a table emailaddress in the database. The table emailaddress has 2 fields 1. idemailaddress and 2. emailaddress, but I am still getting error trying to pull data, please help
Agreement_ctrl
$data['department_list'] = $this->Main_model->get_department_list();
$data['unit_list'] = $this->Main_model->get_unit_list();
$data['terms'] = $this->Main_model->get_terms_list();
$data['emailaddress_list'] = $this->Main_model->get_emailaddress_list();
$data['managers_list'] = $this->Main_model->get_managers_list();
$data['mtnlocation_list'] = $this->Main_model->get_mtnlocation_list();
$data['institution_list'] = $this->Main_model->get_institution_list();
$this->form_validation->set_rules('name', 'Name', 'required');
$this->form_validation->set_rules('gender', 'Gender', 'alpha|xss_clean');
$this->form_validation->set_rules('department', 'Department');
$this->form_validation->set_rules('unit', 'Unit', 'numeric|xss_clean');
Main Model File
}
function get_emailaddress_list()
{
$this->db->order_by('emailaddress', 'ASC');
$query = $this->db->get('emailaddress');
if ($query->num_rows() > 0)
{
foreach ($query->result() as $row)
{
$result [$row->id] = $row;
}
return $result;
}else{
return FALSE;
}
}
Form Page
<div class="form-group row">
<label class="col-sm-3 col-form-label" for="Email">Email Address:</label>
<div class="col-sm-9">
<select name="Email" class="Email form-control" id="Email">
<option value="" <?php echo set_select('Email', ''); ?> >-Select-</option>
<?php if($emailaddress_list){
foreach($emailadress_list as $emailaddress){ ?>
<option value="<?php echo $emailadress->idemailaddress?>" <?php echo set_select('Email', $emailaddress->idemailaddress); ?>><?php echo $emailaddress->emailaddress?></option>
<?php }
}?>
</select>
</div>
</div>
You don't need the foreach loop in your model, just return the query result.
function get_emailaddress_list(){
$this->db->order_by('emailaddress', 'ASC');
$query = $this->db->get('emailaddress');
$data = ($query->num_rows())? $query->result():false;
return $data;
}
Then you loop through this results in your view to create the select options:
<select name="Email" class="Email form-control" id="Email">
<?php if($emailaddress_list):?>
<option value="" disabled selected>-Select-</option>
<?php foreach($emailadress_list as $row): ?>
<option value="<?=$row->idemailaddress?>">
<?=$row->emailaddress?>
</option>
<?php endforeach;?>
<?php else:?>
no records found
<?php endif;?>
</select>

multiple checkbox check if value in database?

code:
<?php
$id = $_GET['id'];
$sql = "select * from admin_menu where id = '$id'";
$result = mysqli_query($link,$sql);
while ($row = mysqli_fetch_array($result))
{
$menu_name = $row['menu_name'];
$menu_link = $row['menu_link'];
$priority = $row['priority'];
$admin_id = explode(",", $row['admin_id']);
}
if(isset($_POST['update']))
{
$admin_id = $_POST['admin_id'];
$chk="";
foreach($admin_id as $chk1)
{
$chk .= $chk1.",";
}
$menu_name = $_POST['menu_name'];
$menu_link = $_POST['menu_link'];
$priority = $_POST['priority'];
$sql = "update admin_menu set menu_name = '$menu_name', menu_link = '$menu_link', priority = '$priority', admin_id = '$chk' where id = '$id'";
$result = mysqli_query($link,$sql);
if($result == true)
{
$msg .= "<h3 style='color:green;'>update</h3>";
}
else
{
$msg .= "<h3 style='color:red;'>Error!</h3>";
}
}
?>
<form name="myform" method="post" >
<div class="row">
<label for="Producer_firstname">Admin Name</label>
<?php
foreach ($admin_id as $admin_id)
{
$chk = "";
if (in_array($chk, $admin_id))
{
$chk = 'checked="checked" ';
}
echo '<input type="checkbox" name="admin_id[]" value="'.$admin_id.'" '.$chk.'/><br/>';
}
?>
</div>
<div class="row">
<label for="Producer_firstname">Menu Name </label>
<input size="60" maxlength="255" name="menu_name" id="menu_name" value="<?php echo $menu_name; ?>" type="text" />
</div>
<div class="row">
<label for="Producer_lastname" >Menu Link </label>
<input size="60" maxlength="255" name="menu_link" id="menu_link" type="text" value="<?php echo $menu_link; ?>" />
</div>
<div class="row">
<label for="Producer_lastname" >Priority</label>
<select name="priority" id="priority">
<option value="<?php echo $priority; ?>"><?php echo $priority; ?></option>
<option value="">choose any one</option>
<option value="1">1</option>
<option value="0">0</option>
</select>
</div>
<div class="row buttons">
<button type="submit" name='update' id='update'>update Menu</button>
</div>
</form>
In this code I am fetching multiple checkbox value from table admin2 and I want when I update form value checkbox check if the value of checkbox is exist into database. How can I fix it ?
Thank You
Your code has few issues,
1. Update should be done before select query
2. List of admin not managed separately
3. Priority radio buttons not managed properly
Additional Suggestions,
1. Use prepare query statements
2. use implode for appending multiple values instead of foreach
3. print admin names before checkboxes
<?php
$id = $_GET['id'];
if(isset($_POST['update']))
{
$chk = implode(',', $_POST['admin_id']);
$menu_name = $_POST['menu_name'];
$menu_link = $_POST['menu_link'];
$priority = $_POST['priority'];
$sql = "update admin_menu set menu_name = '$menu_name', menu_link = '$menu_link', priority = '$priority', admin_id = '$chk' where id = '$id'";
$result = mysqli_query($link,$sql);
$msg = "";
if($result == true)
{
$msg .= "<h3 style='color:green;'>update</h3>";
}
else
{
$msg .= "<h3 style='color:red;'>Error!</h3>";
}
echo $msg;
}
$sql = "select * from admin_menu where id = '$id'";
$result = mysqli_query($link,$sql);
$row = mysqli_fetch_array($result);
$menu_name = $row['menu_name'];
$menu_link = $row['menu_link'];
$priority = $row['priority'];
$admin_id = explode(",", $row['admin_id']);
$admins = array('admin1', 'admin2', 'admin3', 'admin4', 'admin5', 'admin6', 'admin7', 'admin8');
?>
<form name="myform" method="post" >
<div class="row">
<label for="Producer_firstname">Admin Name</label>
<?php
foreach ($admins as $admin)
{
$chk = "";
if (in_array($admin, $admin_id))
{
$chk = 'checked="checked" ';
}
echo $admin.' <input type="checkbox" name="admin_id[]" value="'.$admin.'" '.$chk.'/><br/>';
}
?>
</div>
<div class="row">
<label for="Producer_firstname">Menu Name </label>
<input size="60" maxlength="255" name="menu_name" id="menu_name" value="<?php echo $menu_name; ?>" type="text" />
</div>
<div class="row">
<label for="Producer_lastname" >Menu Link </label>
<input size="60" maxlength="255" name="menu_link" id="menu_link" type="text" value="<?php echo $menu_link; ?>" />
</div>
<div class="row">
<label for="Producer_lastname" >Priority</label>
<select name="priority" id="priority">
<option value="1" <?php if($priority == 1) echo "selected='selected'"; ?>>1</option>
<option value="0" <?php if($priority == 0) echo "selected='selected'"; ?>>0</option>
</select>
</div>
<div class="row buttons">
<button type="submit" name='update' id='update'>update Menu</button>
</div>
</form>

How to insert multiple textboxes with two different names?

enter image description hereI'm trying to insert multiple text-boxes with only two names.In all these texboxes I have names items[] and qty[]. I have tried to nest foreach loop but adds more values than expected.The problem is with $_POST['qty']. I can select and add from items[], but I can not add the qty integer value!
<div class="col-md-12 diff">
<div class="col-md-4">
<p>Select Item</p>
<input style="color:black;" type="text" class="form-control items" name="items[]" placeholder="Search...">
<div class="side"></div>
</div>
<div class="col-md-2">
<p>QTY</p>
<input id="pats_input" class="form-control pats_tb" type="text" name="qty[]" placeholder="NO:">
<div class="side"></div>
</div>
</div>
<div class="col-md-12 diff">
<div class="col-md-4">
<p>Select Item</p>
<input style="color:black;" type="text" class="form-control items" name="items[]" placeholder="Search...">
<div class="side"></div>
</div>
<div class="col-md-2">
<p>QTY</p>
<input id="pats_input" class="form-control pats_tb" type="text" name="qty[]" placeholder="NO:">
<div class="side"></div>
</div>
</div>
function issueToEmployee(){
global $conn;
if(isset($_POST['pats']) && $_POST['pats'] !="" && isset($_POST['items']) && $_POST['items'] !="" && isset($_POST['qty'])){
$perstat = new getPerstat();
//get employee pats
$perstat->getPats($_POST['pats']);
$stock = new StockTable();
$qty = $_POST['qty'];
foreach($_POST['items'] as $item){
foreach($qty as $q){
if(!empty($item) && !empty($q)){
$stock->getItemByName($item);
$sql = $conn->prepare("INSERT INTO issues (empid, itemid) VALUES('$perstat->id','$stock->itemid')");
$sql->execute();
}
}
}
return true;
}else{
return false;
}
I think you're trying to point the items on the qty like this:
$items = $_POST['items'];
$qty = $_POST['qty'];
foreach($items as $i => $item)
{
if(!empty($item) && (isset($qty[$i]) && !empty($qty[$i])))
{
$stock->getItemByName($item);
$sql = $conn->prepare("INSERT INTO issues (empid,itemid) VALUES('$perstat->id','$stock->itemid')");
$sql->execute();
}
}
Since Items are corresponds to their qty (correct me if I'm wrong)
I found how to add above values from multiple input fields items[] and qty[],
for($i = 0; $i < 8 ; $i++){
//$id = $_POST['id'][$i];
$description = $_POST['items'][$i];
$qty = $_POST['qty'][$i];
$date = $_POST['date'];
if(!empty($qty)){
$stock->getItemByName($description);
$sql = $conn->prepare("INSERT INTO issues (empid, itemid, qty, date) VALUES('$perstat->id','$stock->itemid','$qty','$date')");
$sql->execute();
}
}

Categories