Prevent empty multiple inputs from insertion to data base mysql - php

I have a 200 inputs ( 200 rows ) in my web page , the back end user some time enter 20 or 50 inputs and left the rest empty
how to prevent empty inputs from insertion to db
I get around that by deleting the rows with condition but is consuming time
this is my code
<?php
include("db.php");
include("header.php");
if (isset($_POST['invoice_btn'])) {
$userId = $_POST['userId'];
$invoice_to = $_POST['companyName'];
$subTotal = $_POST['subTotal'];
$taxAmount = $_POST['taxAmount'];
$taxRate = $_POST['taxRate'];
$totalAftertax = $_POST['totalAftertax'];
$amountPaid = $_POST['amountPaid'];
$amountDue = $_POST['amountDue'];
$notes = $_POST['notes'];
$productCode = $_POST['productCode'];
$productName = $_POST['productName'];
$quantity = $_POST['quantity'];
$price = $_POST['price'];
$total = $_POST['total'];
$dateTime = $_POST['dateTime'];
$submitbutton = $_POST['invoice_btn'];
if ($submitbutton) {
if (empty($productCode)) {
die(" Product code empty ");
} else {
$sqlInsert = "INSERT INTO invoice_order (invoice_to,order_date, order_total_before_tax, order_total_tax, order_tax_per, order_total_after_tax, order_amount_paid, order_total_amount_due, notes)
VALUES ('$invoice_to' ,'$dateTime', '$subTotal', '$taxAmount','$taxRate', '$totalAftertax','$amountPaid', '$amountDue','$notes')";
$result = mysqli_query($conn, $sqlInsert);
// The mysqli_insert_id() function returns the id (generated with AUTO_INCREMENT) from the last query.
$lastInsertId = mysqli_insert_id($conn);
foreach ($productCode as $index => $productCodes) {
$s_productCode = $productCodes;
$s_productName = $productName[$index];
$s_quantity = $quantity[$index];
$s_price = $price[$index];
$s_total = $total[$index];
$sqlInsertItem = "INSERT INTO invoice_order_item (order_id, item_code, item_name, order_item_quantity, order_item_price, order_item_final_amount)
VALUES ( '$lastInsertId' , '$s_productCode' , '$s_productName' , '$s_quantity', '$s_price', '$s_total')";
$result2 = mysqli_query($conn, $sqlInsertItem);
// Update Quantity on Hand from Produc table
$sqlUpdateQty = "UPDATE product SET pro_quantity = pro_quantity-$s_quantity WHERE pro_id = $s_productCode ";
$result3 = mysqli_query($conn, $sqlUpdateQty);
//delete extra rows that are empty .
$sqlDelete = "DELETE FROM `invoice_order_item` WHERE `item_code`=''";
$Delresult = mysqli_query($conn, $sqlDelete);
} // end foreach
}; // end else
} // end if

In your foreach loop, add a condition before the insertion:
if (empty($s_productCode)) continue;
If the condition becomes true, continue will make the parser skip the rest of the code in the loop.

Related

Data not inserting to database table

When I choose the expandable radio button and press the save button it should save its data to inventory_status table but the data wont insert into the inventory_status table. I've seen similar questions but still couldn't figure out the cause of the problem.
<?php
if($_POST['save']){
if ($_POST['supply_type'] == "expandable"){
$insertI = (mysqli_query($connect, "INSERT INTO inventory_status(stock_prop_no, unit, description, quantity, price) VALUES ('".$sp_num."','".$unit."','".$desc."','".$qty."','".$cost."')"));
}
$pr_no = $_POST['pr_no'];
$s = mysqli_query($connect,"SELECT purchase_no FROM `sms_request` WHERE purchase_no = '".$pr_no."'");
if(mysqli_num_rows($s) > 0)
{
echo"
<script type='text/javascript'>
alert('Purchase No. Existed!');
window.location.href = 'sms_supply management.php';
</script>
";
}
else{
$fcluster = $_POST['fund_cluster'];
$osection = $_POST['office_section'];
$pr_no = $_POST['pr_no'];
$rcode = $_POST['responsibility_code'];
$desig = $_POST['desig'];
$requester = $_POST['requester'];
$loc = $_POST['loc'];
$purpose = $_POST['prpose'];
$ename = $_POST['entity_name'];
$date = $_POST['date'];
$dateA = date("Y-m-d",strtotime($date));
$radioo = $_POST['supply_type'];
$ins = mysqli_query($connect, "INSERT INTO sms_purchaserecord(purchase_no, supply_type) VALUES ('".$pr_no."', '".$radioo."')");
$insS = mysqli_query($connect, "INSERT INTO sms_ris(purchase_no, ris_num) VALUES ('".$pr_no."', '".$pr_no."')");
$insert = mysqli_query($connect, "INSERT INTO sms_request(purchase_no,sms_request.date, entity_name, fund_cluster, office_section, responsibility_code, purpose, stat) VALUES ('".$pr_no."','".$dateA."','".$ename."', '".$fcluster."', '".$osection."', '".$rcode."','".$purpose."', '1')");
$inS = mysqli_query($connect, "INSERT INTO sms_iar(iar_num, purchase_no) VALUES ('".$pr_no."', '".$pr_no."')");
$select = mysqli_query($connect, "SELECT request_IDnum FROM sms_request WHERE purchase_no = '".$pr_no."'");
while ($row = mysqli_fetch_array($select)){
$rnum = $row['request_IDnum'];
}
$select2 = mysqli_query($connect, "SELECT * FROM sms_branchloc WHERE loc_ID_no = '".$loc."'");
while ($row1 = mysqli_fetch_array($select2)){
$loc_num = $row1['loc_ID_no'];
}
if ($rnum != NULL AND $loc_num != NULL){
$insert2 = mysqli_query($connect, "INSERT INTO sms_requester(request_IDnum, name, loc_ID_no, position) VALUES ('".$rnum."', '".$requester."', '".$loc_num."', '".$desig."')");
}
foreach ($_POST['sp_num'] as $row=>$sp_numm) {
$sp_num = $sp_numm;
$unit = $_POST['unt'][$row];
$desc = $_POST['sdesc'][$row];
$qty = $_POST['sqty'][$row];
$cost = $_POST['cost'][$row];
$query = mysqli_query($connect,"INSERT INTO sms_supply (supply_qty,purchase_no,unit_cost,supply_unit,supply_desc,stockproperty_num) VALUES ('".$qty."','".$pr_no."', '".$cost."', '".$unit."','".$desc."', '".$sp_num."')");
}
echo"
<script type='text/javascript'>
alert('Purchase Request Save.');
window.location.href = 'sms_supply management.php';
</script>
";
}
}
This is the table structure of our inventory_status table:
I found one issue on your following query. sms_request.date should be sms_request_date
$insert = mysqli_query($connect, "INSERT INTO sms_request(purchase_no,sms_request.date, entity_name, fund_cluster, office_section, responsibility_code, purpose, stat) VALUES ('".$pr_no."','".$dateA."','".$ename."', '".$fcluster."', '".$osection."', '".$rcode."','".$purpose."', '1')");
Other thing
All these '".$sp_num."','".$unit."','".$desc."','".$qty."','".$cost."')" variables are not defined. so you have to take this condition in loop.
For i.e.
foreach ($_POST['sp_num'] as $row=>$sp_numm) {
$sp_num = $sp_numm;
$unit = $_POST['unt'][$row];
$desc = $_POST['sdesc'][$row];
$qty = $_POST['sqty'][$row];
$cost = $_POST['cost'][$row];
if ($_POST['supply_type'] == "expandable"){
$insertI = (mysqli_query($connect, "INSERT INTO inventory_status(stock_prop_no, unit, description, quantity, price) VALUES ('".$sp_num."','".$unit."','".$desc."','".$qty."','".$cost."')"));
}
$query = mysqli_query($connect,"INSERT INTO sms_supply (supply_qty,purchase_no,unit_cost,supply_unit,supply_desc,stockproperty_num) VALUES ('".$qty."','".$pr_no."', '".$cost."', '".$unit."','".$desc."', '".$sp_num."')");
}

How to fetch record to sum upto a value and then add into two new tables?

I am trying to sum (add the values) from the database. My application checks the values from each row, adds up the value from each row up to 2000. And once it reaches up to 2000, it saves in the database (insert query) and continues the same till last record fetched. The total value summed (or totaled) up by each rows should not exceed over 2000.
There are two insert queries, One for inserting the total( from each row between 1800 and 2000) with the ID (like Primary key) generated and the second table add each row inserted with ID (the ID generated becomes now foreign key)
Please refer to the screenshot.
Please find the code below:
$i = 1;
do {
$id = $row_FetchRecordRS['ID'];
$dateissued = $row_FetchRecordRS['DateIssued'];
$rundateCarrierRun = $row_FetchRecordRS['RundateCarrierRunID'];
$timegenerated = $row_FetchRecordRS['TimeGenerated'];
$carrierID = $row_FetchRecordRS['CarrierRunID'] ;
$areaID = $row_FetchRecordRS['CarrierAreaID'];
$address = $row_FetchRecordRS['DeliveryAddress'];
$potzone = $row_FetchRecordRS['Postzone'];
$carr_ID = $row_FetchRecordRS['CarrierID'];
$instruction = $row_FetchRecordRS['DeliveryAddress'];
$areaRep = $row_FetchRecordRS['AreaRepDetails'];
// $vendor = $row_FetchRecordRS['VendorDetails'];
$quantity = $row_FetchRecordRS['Quantity'];
$direct = $row_FetchRecordRS['Direct'];
$jobID = $row_FetchRecordRS['JobID'];
$jobName = $row_FetchRecordRS['JobName'];
$bundlesize = $row_FetchRecordRS['Bundlesize'];
$bundle = $row_FetchRecordRS['Bundles'];
$items = $row_FetchRecordRS['Items'];
$weight = $row_FetchRecordRS['WeightKgs'];
$totalWeightCol = $row_FetchRecordRS['TotalWeightKgs'];
$date = date("D M d, Y G:i");
$total_weight = $row_FetchRecordRS['FinalWeight'] + $total_weight ;
echo "Row: " .$row_FetchRecordRS['FinalWeight']. "<br>";
echo "Total is______ $i : $total_weight <br><br>";
$sqlquerytest = "INSERT INTO `GenerateRun`
(`DateIssued`, `RundateCarrierRunID`, `TimeGenerated`,
`CarrierRunID`, `CarrierAreaID`, `DeliveryAddress`, `Postzone`,
`CarrierID`, `DeliveryInstruction`, `AreaRepDetails`,
`Quantity`, `Direct`, `JobID`, `JobName`, `Bundlesize`,
`Bundles`, `Items`, `WeightKgs`, `TotalWeightKgs`,
`LodingZoneID`)
VALUES
('$dateissued', '$rundateCarrierRun', '$timegenerated',
'$carrierID', '$areaID', '$address', '$potzone', '$carr_ID',
'$instruction', '$areaRep', '$quantity', '$direct', '$jobID',
'$jobName', '$bundlesize', '$bundle', '$items', '$weight',
'$totalWeightCol','$i')";
mysql_select_db($database_callmtlc_SalmatDB, $callmtlc_SalmatDB);
$ResultUpd1 = mysql_query($sqlquerytest, $callmtlc_SalmatDB) or die(mysql_error());
if ($total_weight >= 1800) {
$sqltransitlist = " INSERT INTO `TransitList`(`genID`, `total`) Values ('$i','$total_weight')";
mysql_select_db($database_callmtlc_SalmatDB, $callmtlc_SalmatDB);
$ResultUpd3 = mysql_query($sqltransitlist, $callmtlc_SalmatDB) or die(mysql_error());
$i = $i+1;
$total_weight = 0;
}
} while($row_FetchRecordRS = mysql_fetch_assoc($FetchRecordRS));
Some of your line of codes are irrelevant to your problem. I will simplify it for you.
$i = 1;
$total = 0;
$arr = array(); // for storing a list of data provides that the total doesn't exceed 2000
while ($row = mysql_fetch_assoc($record)) {
$id = $row['id'];
$name = $row['name'];
$num = $row['num'];
$arr[] = array('id' => $id, 'name' => $name, 'num' => $num);
if ($num + $total > 2000) {
$sql = "INSERT INTO Table1(genID, total) Values ('$i','$total')";
mysql_query($sql) or die(mysql_error());
foreach ($arr as $data) {
$sql = "INSERT INTO Table2(ID, name, genID, total) Values ('$data[id]','$data[name]','$i','$data[num]')";
mysql_query($sql) or die(mysql_error());
}
$arr = array(); // empty the array as the data has been stored to database
$i++;
$total = 0;
} else { // if the total doesn't exceed 2000, add it to total
$total += $num;
}
}
$sql = "INSERT INTO Table1(genID, total) Values ('$i','$total')";
mysql_query($sql) or die(mysql_error());
foreach ($arr as $data) {
$sql = "INSERT INTO Table2(ID, name, genID, total) Values ('$data[id]','$data[name]','$i','$data[num]')";
mysql_query($sql) or die(mysql_error());
}
Note: this code is just a sample, not your actual code. You can implement my code and match it to your code.

Having error when inserting my item name to my phpmyadmin table

SO i want to insert my item id and together with my item name into a distribution_item,it only insert item id but not the name because of the array
i use item[$i] whenever there is a item in the table row, so it get the data and insert.
#$recipient = $_POST['recipient'];
#$address = $_POST['address'];
#$contact = $_POST['contact'];
#$date = $_POST['in_date'];
#$itemID = $_POST['id'];
#$remark = $_POST['remark'];
#$spec_remark = $_POST['spec_remark'];
$itemBalance = $_POST["count"];
$count = count($itemID);
// authentication to the database
$servername = "localhost";
$username = "root";
$password = "";
$dbName = "hopeplace";
//Create connection
$Conndb = mysqli_connect($servername, $username, $password, $dbName);
// Check connection
if (!$Conndb) {
die("Connection failed: " . $Conndb->connect_error);
}
else {
// select database
mysqli_select_db($Conndb, $dbName);
$full_name = "SELECT * FROM recipient WHERE `FULL_NAME` = '$recipient'";
$result = mysqli_query($Conndb, $full_name);
$rec = mysqli_fetch_array($result);
$recipient_id = $rec['HP_ID'];
$item_id = "SELECT ITEM_NAME FROM inventory WHERE ITEM_ID = '$itemID'";
$result2 = mysqli_query($Conndb, $item_id);
$rec2 = mysqli_fetch_array($result2);
$item_name = $rec2["ITEM_NAME"];
$string = implode(',',$item_id);
$sql = "SHOW TABLE STATUS WHERE `Name` = 'distribution';";
$result = mysqli_query($Conndb, $sql);
$data = mysqli_fetch_assoc($result);
$DISTRIBUTION_ID = $data['Auto_increment'];
// Add into distribution table
$sql = "INSERT INTO distribution(DISTRIBUTION_ID,HP_ID,FULL_NAME, ADDRESS, CONTACT, DISTRIBUTION_DATE, SPEC_REMARK) VALUES ('$DISTRIBUTION_ID','$recipient_id','$recipient', '$address', '$contact', '$date', '$spec_remark')";
if (mysqli_query($Conndb, $sql)) {
//Add item into distribution_item table
$item_count = 0;
for ($i=0; $i<$count; $i++){
$sql = "INSERT INTO distribution_item (DISTRIBUTION_ID, ITEM_ID,ITEM_NAME,OUT_QUANTITY,REMARK) VALUES ('$DISTRIBUTION_ID', '$itemID[$i]','$string[$i]','$itemBalance[$i]', '$remark[$i]')";
if (mysqli_query($Conndb, $sql)){
$out = "UPDATE inventory set QUANTITY = QUANTITY - '$itemBalance[$i]' where ITEM_ID= '$itemID[$i]'";
mysqli_query($Conndb, $out);
//echo "<p>Item $itemID[$i] has been added to $DISTRIBUTION_ID</p>";
$item_count++;
} else {
echo "Error: $sql <br />" . mysqli_error($Conndb);
}
}
if ($item_count == $count){
echo "<div>
<script>
window.alert('Record added successfully!');
</script>
</div>";
}
} else {
echo "Error: $sql <br />" . mysqli_error($Conndb);
}
}
mysqli_close($Conndb);
?>
it pop out an error like this
Notice: Array to string conversion in C:\xampp\htdocs\hopeplace\distribution\add_distribution.php on line 55
Warning: implode(): Invalid arguments passed in C:\xampp\htdocs\hopeplace\distribution\add_distribution.php on line 56
it seems like i have to convert my array to string so i can pass the value into table. my database table is something like this
DISTRIBUTION_ID | ITEM_NAME | ITEM_NAME|
1 1 APPLE
1 2 ORANGE
The problem here is that $string[$i] cannot be found because no $string array exists, since $string = implode(', ',$item_id) can only work if $item_id is an array.
In the question, $item_id = "SELECT ITEM_NAME FROM inventory WHERE ITEM_ID = '$itemID'"; gives $item_id as a string. That is why the warning error indicates that the implode function cannot work. The notice error shows that you cannot get an array element from the $string variable, and this is because that variable is not an array.
To get $string as an array, you would have to correct the following code:
$item_id = "SELECT ITEM_NAME FROM inventory WHERE ITEM_ID = '$itemID'";
$result2 = mysqli_query($Conndb, $item_id);
$rec2 = mysqli_fetch_array($result2);
$item_name = $rec2["ITEM_NAME"];
$string = implode(',',$item_id);
For example, the above code could be changed to the following:
$string = [];
$item_id = "SELECT ITEM_NAME FROM inventory WHERE ITEM_ID = '$itemID'";
$result2 = mysqli_query($Conndb, $item_id);
while($rec2 = mysqli_fetch_array($result2){
$string[] = $rec2["ITEM_NAME"];
}
Then in the sql query for inserting the item name you would first define the counting variable as $count = count($string);

For loop only loop one time

i have this code, suppose loop 5 time but it only loop one time only. How to make sure it will loop 5 time?.
for ($i = 0; $i < 5;)
{
$sql6 = "SELECT * FROM at_agent_management WHERE piam_reg = '$checkedValuesarr[$i]'";
$result6 = mysql_query($sql6);
while($row6 = mysql_fetch_array($result6)){
$reg = $row6['piam_reg'];
$date = $row6['piam_date'];
$agency = $row6['agency_name'];
$branch = $row6['branch'];
$category = $row6['agent_category'];
//$template_id = $reg_count;
$sql7 = "INSERT INTO at_agent_view_receipant(piam_reg, piam_date, agency_name, branch, agent_category, template_id) VALUES ('$reg', '$date', '$agency', '$branch', '$category', '$reg_count')";
$result7 = mysql_query($sql7);
}
$i++;
}
From logic you have written,
There is checkbox values array and you want to use that value in Query.
You can try with Foreach Loop as below,
<?
$checkedValuesarr=array("1","2","3","4","5");
foreach ($checkedValuesarr as $checkValue)
{
$sql6 = "SELECT * FROM at_agent_management WHERE piam_reg = '".$checkValue."'";
$result6 = mysql_query($sql6);
while($row6 = mysql_fetch_array($result6)){
$reg = $row6['piam_reg'];
$date = $row6['piam_date'];
$agency = $row6['agency_name'];
$branch = $row6['branch'];
$category = $row6['agent_category'];
//$template_id = $reg_count;
$sql7 = "INSERT INTO at_agent_view_receipant(piam_reg, piam_date, agency_name, branch, agent_category, template_id) VALUES ('$reg', '$date', '$agency', '$branch', '$category', '$reg_count')";
$result7 = mysql_query($sql7);
}
}?>

Grab info from multiple sql tables and put into one using php

At the moment this code updates the user info in MYSQLTABLE1. What I also want done is user info to be copied to WMYSQLTABLE which I can do but I also want a code from MYSQLTABLE2 to be copied over into a column in WMYSQLTABLE as well. Here is the part I need changing:
$sql_insert2 = "INSERT INTO ".WMYSQLTABLE2."(ip,date,address)values
('','$ip','$date','$address')";
$res_insert2 = mysql_query($sql_insert2)or die(mysql_error());
//Need to also insert code from first row from column named 'codes' in MYSQLTABLE2.
Actual code, it's a bit messy at the moment and the if/else statements do the exact same at the moment. It works but I get the error " Column count doesn't match value count at row 1" because I cannot fill the last column with the code from MYSQLTABLE2.
<?php
include("includes/config.php");
include("includes/mysql.php");
include("amount.php");
if(isset($_POST['func']))
{
$address = $_POST['address'];
$ip = $_POST['ip'];
$date = $_POST['date'];
$time = $_POST['time'];
$price = $_POST['price'];
$increment = $_POST['increment'];
$id = $_POST['id'];
$num = 0;
$sql_check_address = "SELECT * FROM ".MYSQLTABLE1." WHERE address='$address'";
$res_check_address = mysql_query($sql_check_address)or die(mysql_error());
$num = mysql_num_rows($res_check_address);
$row = mysql_fetch_assoc($res_check_address);
if($num > 0)
{
$address = $row['address'];
$ip = $row['ip'];
$date = $row['date'];
$oldprice = $row['price'];
$id = $row['id'];
$newprice = $oldprice - $payAmount*200;
$newinc = $increment - 200;
$sql_update1 = "UPDATE ".MYSQLTABLE1." SET ip='$ip',date='$date',price='$newprice',increment='$newinc',address='$address' WHERE id='$id'";
$res_update1 = mysql_query($sql_update1)or die(mysql_error());
/////////////////Insert user info and copy code from MYSQLTABLE2 to WMYSQLTABLE2
$sql_insert2 = "INSERT INTO ".WMYSQLTABLE2."(ip,date,address)values
('','$ip','$date','$address')";
$res_insert2 = mysql_query($sql_insert2)or die(mysql_error());
}
else{
$address = $row['address'];
$ip = $row['ip'];
$date = $row['date'];
$oldprice = $row['price'];
$id = $row['id'];
$newprice = $oldprice - $payAmount*200;
$newinc = $increment - 200;
$sql_update = "UPDATE ".MYSQLTABLE1." SET ip='$ip',date='$date',price='$newprice',increment='$newinc',address='$address' WHERE id='$id'";
$res_update = mysql_query($sql_update)or die(mysql_error());
/////////////////Insert user info and copy code from MYSQLTABLE2 to WMYSQLTABLE2
$sql_insert2 = "INSERT INTO ".WMYSQLTABLE2."(ip,date,address)values
('','$ip','$date','$address')";
$res_insert2 = mysql_query($sql_insert2)or die(mysql_error());
e
}
}
Any help will be greatly appreciated.
The general form of the query would be:
$sql_insert = "INSERT INTO " . WMYSQLTABLE2 . "(code, ip, date, address)
SELECT code, '$ip', '$date', '$address'
FROM OtherTable
WHERE <put something here to select the row>";

Categories