How to insert multiple textboxes with two different names? - php

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();
}
}

Related

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>

Insert, Update, Search in MySql database using PHP

This is my first post in this forum, despite being a devoted follower for years now.
I have built a simple system that registers lot numbers and their locations within a MySQL database through a PHP form.
Then i have this other form called "Errata Corrige" that I use to find and edit eventual mistaken entries.
It's search criteria is an (UNSIGNED INT UNIQUE) value named "lotto" and everything works (worked) like a charm under this circumstances.
Now the thing got a little tricky.
I found out that lot numbers (lotto) for work purposes are not always unique values, there might be more than one entry with the same number.
No problem making the "Insert" form or various counters work under this new circumstances, but it got really tricky within the EDIT functions.
This is my PHP code: `
<?php
$id = "";
$settore = "";
$ubicazione = "";
$numero = "";
$lotto="";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// connect to mysql database
try{
$connect = mysqli_connect($host, $user, $password, $database);
} catch (mysqli_sql_exception $ex) {
echo 'Error';
}
// get values from the form
function getPosts()
{
$posts = array();
$posts[0] = $_POST['id'];
$posts[1] = $_POST['settore'];
$posts[2] = $_POST['ubicazione'];
$posts[3] = $_POST['numero'];
$posts[4] = $_POST['lotto'];
return $posts;
}
// Search
if(isset($_POST['search']))
{
$data = getPosts();
$search_Query = "SELECT * FROM mappa WHERE lotto = $data[4]";
$search_Result = mysqli_query($connect, $search_Query);
if($search_Result)
{
if(mysqli_num_rows($search_Result))
{
while($row = mysqli_fetch_array($search_Result))
{
$id = $row['id'];
$settore = $row['settore'];
$ubicazione = $row['ubicazione'];
$numero = $row['numero'];
$lotto = $row ['lotto'];
}
}else{
echo 'Lotto non presente in archivio';
}
}else{
echo 'Error';
}
}
// Insert
if(isset($_POST['insert']))
{
$data = getPosts();
$insert_Query = "INSERT INTO `mappa`(`settore`, `ubicazione`, `numero`, `lotto` ) VALUES ('$data[1]','$data[2]',$data[3], $data[4])";
try{
$insert_Result = mysqli_query($connect, $insert_Query);
if($insert_Result)
{
if(mysqli_affected_rows($connect) > 0)
{
$resInsert = "1 nuovo dato inserito correttamente!";
}else{
$resInsert = "Nessun dato inserito";
}
}
} catch (Exception $ex) {
echo 'Errore '.$ex->getMessage();
}
}
// Edit
if(isset($_POST['update']))
{
$data = getPosts();
$update_Query = "UPDATE `mappa` SET `settore`='$data[1]',`ubicazione`='$data[2]',`numero`=$data[3],`lotto`=$data[4] WHERE `id` = $data[0]";
try{
$update_Result = mysqli_query($connect, $update_Query);
if($update_Result)
{
if(mysqli_affected_rows($connect) > 0)
{
$resAgg = "1 dato aggiornato correttamente!";
}else{
$resAgg = "Nessun dato aggiornato!";
}
}
} catch (Exception $ex) {
echo 'Error Update '.$ex->getMessage();
}
} ?>
`
HTML:
<form action="mod.php" method="post" class="form-horizontal form-bordered" style="text-align:center">
<div class="form-group has-error" style="padding-top:30px">
<label class="col-xs-3 control-label" for="state-normal">ID</label>
<div class="col-lg-3">
<input type="text" name="id" placeholder="ID" class="form-control" value="<?php echo $id;?>"> </div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="state-normal">Settore</label>
<div class="col-md-6">
<input type="text" name="settore" placeholder="Settore" class="form-control" value="<?php echo $settore;?>"> </div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="state-normal">Ubicazione</label>
<div class="col-md-6">
<input type="text" name="ubicazione" placeholder="Ubicazione" class="form-control" value="<?php echo $ubicazione;?>"> </div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="state-normal">Numero</label>
<div class="col-md-6">
<input type="text" name="numero" placeholder="Numero" class="form-control" value="<?php echo $numero;?>"> </div>
</div>
<div class="form-group has-success">
<label class="col-md-3 control-label" for="state-normal">Lotto</label>
<div class="col-md-6">
<input type="text" name="lotto" placeholder="Lotto" class="form-control" value="<?php echo $lotto;?>"> </div>
</div>
<div style="padding-top:16px">
<!-- Insert-->
<button type="submit" name="insert" value="Add" class="btn btn-effect-ripple btn-primary">Inserisci</button>
<!-- Update-->
<button type="submit" name="update" value="Update" class="btn btn-effect-ripple btn-info">Aggiorna</button>
<a> </a>
<!-- Search-->
<button type="submit" name="search" value="Find" class="btn btn-effect-ripple btn-success">Cerca</button>
</div>
</form>
While the lot number was unique everything worked like a charm.
Now that there are multiple data with the same lot number the code became obsolete since the "search" function only shows the last (greatest ID) data.
I have tried to work around a loop and tell the function to search every ID where lotto = lotto but it didn't work.
A simple solution would be obviously searching through ID instead of lotto but that is a pretty crapy one, since the user only knows (and is interested in) Lot Numbers not the ID it was assigned during data insertion.
Then I tried to put two php functions into one page, the first that fetches data from Mysql into a PHP dropdown menu, telling it to show every ID that matches the search criteria (lotto):
<?php if (isset($_POST['submitted'])){
include ('../mysql_connect.php'); // connessione al database
$category = 'lotto';
$criteria = $_POST['criteria'];
$query = "SELECT * FROM mappa WHERE $category = '$criteria'";
$result = mysqli_query($dbcon, $query) or die('Impossibile reperire i dati');
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$idTab = $row['id'];
echo "<option>
$idTab </option>";
}
} // FINE if ?>
</select>
Fetching data from MySQL into the dropdown worked just fine, but I got stucked in the syntax trying to use this dropdown as a search criteria for my first function.
Every help would really be appreciated! Thank you in advance for your answers.
You said that lotto is unique. So how come you are able to insert multiple rows with the same lotto?
Remove the unique constraint from the lotto column.
Try the following:
$query = select lotto, group_concat(id) as ID numbers from mappa where lotto = 'user search number' group by lotto;
$result = $conn->query($query);
$rows = $result->num_rows;
$result->data_seek(0); //move to first row (which is the only one)
$row = $result->fetch_array(MYSQLI_NUM); //fetch array
$id_numbers_string = $row[1]; //store the values of the row's second column (which is number 1)
$id_numbers_separated_array = explode(",", $id_numbers_string); //create an array with the values in the string
for($i = 0; $i < count($id_numbers_separated_array); $i++){ //loop through created array
echo "ID: " . $id_numbers_separated_array[$i];
echo "<br>";
}
Also try to run the query in your database management system to see the results.

Insert several rows at once MySql DB

I have a form with 6 text inputs for users to add some links to them and add them do a database. Each one of these 6 inputs insert data in a different row. This is my code:
public function insertImages($img1,$img2,$img3,$img4,$img5,$img6){
$myDb = $this->_controlPanel->getMyDb();
$query = "INSERT INTO galeria (img) VALUES ('$img1'), ('$img2'),('$img3'), ('$img4'),('$img5'), ('$img6')";
$result = $myDb->performQuery($query);
if (!$result) {
die('Something went wrong, try again: ' . mysql_error());
header( "Refresh:3; url=insertnot.php");
}
else {
header( "Refresh:1; url=admin.php");
}
}
and
if(!empty($_POST)){
$img1 = $_POST['img1'];
$img2 = $_POST['img2'];
$img3 = $_POST['img3'];
$img4 = $_POST['img4'];
$img5 = $_POST['img5'];
$img6 = $_POST['img6'];
try{
$log = new classes_UserManager($myControlPanel);
$insert = $log->insertImagens($img1,$img2,$img3,$img4,$img5,$img6);
}
catch (invalidArgumentException $e){
$e->getMessage();
}
}
?>
<div class="container">
<h2 style="color:#666; margin-top:15vh; text-align:center;"> Inserir Imagens </h2>
<form style="margin-top:10vh;" name="img" method="POST" action="">
<div class="row">
<div class="col-md-4">
<input placeholder="Imagem 1" class="form-control" type="text" name="img1" id="title" >
</div>
<div class="col-md-4">
<input placeholder="Imagem 2" class="form-control" type="text" name="img2" id="title" >
</div>
<div class="col-md-4">
<input placeholder="Imagem 3" class="form-control" type="text" name="img3" id="title" >
</div>
</div>
<br>
<br>
<div class="row">
<div class="col-md-4">
<input placeholder="Imagem 4" class="form-control" type="text" name="img4" id="title" >
</div>
<div class="col-md-4">
<input placeholder="Imagem 5" class="form-control" type="text" name="img5" id="title" >
</div>
<div class="col-md-4">
<input placeholder="Imagem 6" class="form-control" type="text" name="img6" id="title" >
</div>
</div>
<br>
<br>
<input type="submit" style="width:100%; margin:0 auto;" class="btn btn-primary form-control" name="submit" id="submit">
This is working well, but how do i avoid entering blank rows when the user only fills like two or three inputs?
Use the "power" of concatenation. There are few solutions to your problem.
let's consider following function:
<?php
// get all non-empty fields for POST that
// have index like img<number>
function getNonEmptyValues ($inputs , $input_prefix, $inputs_count = 7)
{
$nonempty_inputs = array();
$prefix = isset($input_prefix) ? $input_prefix : '';
// you have to be sure each of your inputs
// is indexed as range 1..N
// with some prefix
for ($i = 1; $i < $inputs_count; $i++)
{
$value = isset($inputs[$prefix.$i]) ? $inputs[$prefix.$i] : '';
if(strlen($value))
{
$nonempty_inputs []= $value;
}
}
return $nonempty_inputs;
}
// get all non-empty fields for POST that
// have index like img<number>
// but ignore all fields after 1 missing,
// e.g. : img1, img2, img3 return array of length 3
// while img1, img2, img4 will return array of length 2
function getInOrder($inputs, $input_prefix, $inputs_count = 7)
{
$nonempty_inputs = array();
$prefix = isset($input_prefix) ? $input_prefix : '';
// you have to be sure each of your inputs
// is indexed as range 1..N
// with some prefix
for ($i = 1; $i < $inputs_count; $i++)
{
$value = isset($inputs[$prefix.$i]) ? $inputs[$prefix.$i] : '';
if(strlen($value))
{
$nonempty_inputs []= $value;
}
else
{
break;
}
}
return $nonempty_inputs;
}
function buildInsertQuery ($inputs) {
if (count($inputs) === 0) {
throw new \Exception("Missing inputs. Cannot build query.");
}
$query = "INSERT INTO galeria (img) VALUES ";
$insert_values = [];
foreach( $inputs as $value ) {
$insert_values []= "('".$value."')";
}
return $query . implode(",", $insert_values) . ";";
}
$_our_post = array(
"img1" => "kittenz",
"img2" => "doge",
"img4" => "me gusta"
);
$my_data = getNonEmptyValues($_our_post, "img");
echo buildInsertQuery($my_data);
echo "\n";
$my_data = getInOrder($_our_post, "img");
echo buildInsertQuery($my_data);
echo "\n";
something like this:
if(!empty($_POST)) {
$images = array();
for ($i = 1; $i <= 6; $i++) {
if (!empty($_POST['img'.$i]))
$images[] = $_POST['img'.$i];
}
if (sizeof($images) > 0)
$insert = $log->insertImages($images);
...
}
and
public function insertImages($images) {
$myDb = $this->_controlPanel->getMyDb();
$imgStr = '';
foreach($images as $k => $v) {
$imgStr += "('$v'),";
}
$imgStr = rtrim($imgStr, ','); // remove trailing comma
$query = "INSERT INTO galeria (img) VALUES $imgStr";
...
}

PHP not inserting into database SQL SERVER 2008

I have this form that I want to use to capture data and insert into a database:
<form actoin="request-new-price.php" method="post" id="demo-form2" data-parsley-validate>
<div>
<label for="salesRep">Sales Rep:</label>
<div>
<input type="text" name="salesRep" id="salesRep" required="required" value="<?php echo $user['userName']; ?>">
</div>
</div>
<div>
<label for="CardName">Customer Name</label>
<div>
<input type="text" id="CardName" name="CardName" required="required" value="<?php echo $selectedCustomerName ?>">
</div>
</div>
<div>
<label for="CardCode">Customer Code</label>
<div>
<input type="text" id="CardCode" name="CardCode" required="required" value="<?php echo $selectedCustomerID ?>">
</div>
</div>
<div>
<label for="ItemName">Product Name</label>
<div>
<input type="text" id="ItemName" name="ItemName" required="required" value="<?php echo $selectedProductName ?>">
</div>
</div>
<div>
<label for="ItemCode">Product Code</label>
<div>
<input type="text" id="ItemCode" name="ItemCode" required="required" value="<?php echo $selectedProductCode ?>">
</div>
</div>
<div>
<label for="Price">Current Price</label>
<div>
<input type="text" id="Price" name="Price" required="required" value="£<?php echo $selectedProductPrice ?>">
</div>
</div>
<div>
<label for="requestedPrice">Requested Price</label>
<div>
<input type="text" id="requestedPrice" name="requestedPrice" required="required" value="£">
</div>
</div>
<div>
<div>
Cancel
<button type="submit" id="submit" name="submit" value="1">Submit</button>
</div>
</div>
</form>
And here is my SQL/PHP:
<?php
if(isset($_POST['submit'])){
print_r($_POST);
$query = prepare("INSERT INTO PriceRequests (salesRep, CardName, CardCode, ItemName, ItemCode, Price, requestedPrice)
VALUES (:salesRep, :cardName, :cardCode, :itemName, itemCode, :itemPrice, :newPrice)
");
$insertSql = sqlsrv_query($sapconn, $query);
$insertSql->bindParam(":salesRep",$salesRep);
$insertSql->bindParam(":cardName",$cardName);
$insertSql->bindParam(":cardCode",$cardCode);
$insertSql->bindParam(":itemName",$itemName);
$insertSql->bindParam(":itemCode",$itemCode);
$insertSql->bindParam(":itemPrice",$itemPrice);
$insertSql->bindParam(":newPrice",$newPrice);
$salesRep = trim($_POST['salesRep']);
$cardName = trim($_POST['CardName']);
$cardCode = trim($_POST['CardCode']);
$itemName = trim($_POST['ItemName']);
$itemCode = trim($_POST['ItemCode']);
$itemPrice = trim($_POST['Price']);
$newPrice = trim($_POST['requestedPrice']);
$insertSql->execute();
return $insertSql;
}
?>
But the data is not inserting into the database I am fairly new to PHP and this is my first attempt at writing back to the database, so I may be missing something simple, or it may be completely wrong.
Either way all help is appreciated.
EDIT:
My PHP is now this:
if(isset($_POST['submit'])){
//print_r($_POST);
$query = "INSERT INTO PriceRequests (salesRep, CardName, CardCode, ItemName, ItemCode, Price, requestedPrice)
VALUES (:salesRep, :cardName, :cardCode, :itemName, :itemCode, :itemPrice, :newPrice)
";
$stmt = $sapconn->prepare($query);
$salesRep = (isset($_POST['salesRep']) && !empty($_POST['salesRep']))?$_POST['salesRep'] : NULL;
$cardName = (isset($_POST['CardName']) && !empty($_POST['CardName']))?$_POST['CardName'] : NULL;
$cardCode = (isset($_POST['CardCode']) && !empty($_POST['CardCode']))?$_POST['CardCode'] : NULL;
$itemName = (isset($_POST['ItemName']) && !empty($_POST['ItemName']))?$_POST['ItemName'] : NULL;
$itemCode = (isset($_POST['ItemCode']) && !empty($_POST['ItemCode']))?$_POST['ItemCode'] : NULL;
$itemPrice = (isset($_POST['Price']) && !empty($_POST['Price']))?$_POST['Price'] : NULL;
$newPrice = (isset($_POST['requestedPrice']) && !empty($_POST['requestedPrice']))?$_POST['requestedPrice'] : NULL;
$stmt->bindValue(':salesRep', $salesRep, PDO::PARAM_STR);
$stmt->bindValue(':cardName', $cardName, PDO::PARAM_STR);
$stmt->bindValue(':cardCode', $cardCode, PDO::PARAM_STR);
$stmt->bindValue(':itemName', $itemName, PDO::PARAM_STR);
$stmt->bindValue(':itemCode', $itemCode, PDO::PARAM_STR);
$stmt->bindValue(':itemPrice', $itemPrice, PDO::PARAM_STR);
$stmt->bindValue(':newPrice', $newPrice, PDO::PARAM_STR);
$stmt->execute();
return $stmt;
}
But i still have no input to my database and i am getting the following error:
PHP Fatal error: Uncaught Error: Call to a member function prepare() on resource
DB Connection:
<?php
$serverName = "serverName";
$connectionInfo = array( "Database"=>"database_name", "UID"=>"user_Id", "PWD"=>"Password", "ReturnDatesAsStrings"=>true);
$sapconn = sqlsrv_connect( $serverName, $connectionInfo);
?>
One more typo in the PHP code :
$query = prepare("INSERT INTO PriceRequests (salesRep, CardName, CardCode, ItemName, ItemCode, Price, requestedPrice)
VALUES (:salesRep, :cardName, :cardCode, :itemName, itemCode, :itemPrice, :newPrice)
");
The placeholder itemCode does not have the suffix ":".
Check that and try.
Thank you.
UPDATE:
I tried something that you wrote in the question. You have tried to bind the parameters to the placeholders before the parameters are assigned.
When I tried to do so, I got exception. I think this may the reason the data is not getting inserted.
I would suggest you to write the code in the following manner :
PHP CODE :
<?php
if(isset($_POST['submit'])){
print_r($_POST); //Unnecessary, you can remove it
$query = prepare("INSERT INTO PriceRequests (salesRep, CardName, CardCode, ItemName, ItemCode, Price, requestedPrice)
VALUES (:salesRep, :cardName, :cardCode, :itemName, :itemCode, :itemPrice, :newPrice)
");
$insertSql = sqlsrv_query($sapconn, $query);
$salesRep = trim($_POST['salesRep']);
$cardName = trim($_POST['CardName']);
$cardCode = trim($_POST['CardCode']);
$itemName = trim($_POST['ItemName']);
$itemCode = trim($_POST['ItemCode']);
$itemPrice = trim($_POST['Price']);
$newPrice = trim($_POST['requestedPrice']);
$insertSql->bindParam(":salesRep",$salesRep);
$insertSql->bindParam(":cardName",$cardName);
$insertSql->bindParam(":cardCode",$cardCode);
$insertSql->bindParam(":itemName",$itemName);
$insertSql->bindParam(":itemCode",$itemCode);
$insertSql->bindParam(":itemPrice",$itemPrice);
$insertSql->bindParam(":newPrice",$newPrice);
$insertSql->execute();
return $insertSql;
}
?>
I would suggest a few change:
1. As PDO is used here, use a variable to get the Database connection (lets assume its $db_conn).
Instead of
$insertSql = sqlsrv_query($sapconn, $query);
use
$db_conn = new PDO(<connection-string>, <user-name>, <password>);
$stmt = $db_conn->prepare($query)
Then bind the value by :
$stmt->bindValue(<placeholder>, <variable_vlaue>, <value_type>);
eg : $stmt->bindValue(:itemName, $itemName, PDO::PARAM_STR);
Then perform execution:
$stmt->execute();
2. If you place some validation of the data it will be helpful :
Assign the value of POST to the variables via a validation
eg :
$itemName = (isset($_POST['ItemName']) && !empty($_POST['ItemName']))?$_POST['ItemName'] : NULL;
Here, when insert query is executed with 'NULL' it will throw an exception.
N.B. : try-catch block should be used.
I think it should work now.
Please feel free to tell if it does not work, I will check again.
you know there is a typo in the first line? Won't submit with that.
<form actoin="request-new-price.php" method="post" id="demo-form2" data- parsley-validate>
change to form action for a start

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

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>";
}
?>

Categories