Do not save empty rows - php

I have a table that contains a list of all products and before each one there is a field "number" in which the user will put the quantity then click on save.
This code save all rows in data base using mutiple-insert but I want that if quantite is null or empty, so do not save this row , I want just save
$managerAchat = new AchatManager($db);
if(isset($_POST['ajouter']))
{
$size = count($_POST['quantite']);
$i = 0;
while ($i < $size)
{
if(isset($_POST['quantite'][$i]))
{
$nomProd = $_POST['nomProd'][$i] ;
$prixProd = $_POST['prixProd'][$i] ;
$quantite = $_POST['quantite'][$i] ;
$date = date('d/m/Y');
$AchatObject = new Achat(array(
'nomProd' => $nomProd ,
'prixProd' => $prixProd ,
'quantite' => $quantite ,
'date' => $date ,
)) ;
$managerAchat->insert($AchatObject);
++$i;
}
}
}

It seems you just need to change:
if(isset($_POST['quantite'][$i]))
to:
if(isset($_POST['quantite'][$i]) && $_POST['quantite'][$i] > 0)
You can also use for example array_filter() to loop only over the keys that have an amount set:
if(isset($_POST['ajouter']))
{
$has_amounts = array_filter($_POST['quantite']);
foreach (array_keys($has_amounts) as $key)
{
$nomProd = $_POST['nomProd'][$key];
// etc.

I'm not 100% sure this is correct as your question and code are not clear. But, you can check to see if $_POST['quantite'][$i] is empty (zero and null will both be considered empty) and skip them if they are:
if(isset($_POST['quantite'][$i]) && !empty($_POST['quantite'][$i]))

Related

How to differentiate between each isset and update a specific table row in PHP

The first part of my code creates some entries in a table using $_POST.
foreach ($_POST['form_item'] as $key => $value) {
$item = $_POST['form_item'][$key];
$barcode = $_POST['form_barcode'][$key];
$task = $_POST['form_task'][$key];
$bottom_items = $pdo->prepare("INSERT INTO carpet_items_extra (`item_id`,`item_task`, `item_barcode`) VALUES ('$log_id', '$task', '$barcode')");
$bottom_items->execute();
The next part contains the data I need to update the entries with.
if(isset($_POST['form_price_standard'][$key]) && $_POST['form_price_standard'][$key] != ''){
$price_standard = $_POST['form_price_standard'][$key];
}
else{
$price_standard = 0;
}
if(isset($_POST['form_price_daily_1'][$key]) && $_POST['form_price_daily_1'][$key] != '' && isset($_POST['form_duration_2'][$key]) && $_POST['form_duration_2'][$key] != ''){
$price_daily_1 = $_POST['form_price_daily_1'][$key];
$duration_2 = $_POST['form_duration_2'][$key];
}
else{
$price_daily_1 = 0;
$duration_2 = 0;
}
$update = $pdo->prepare("UPDATE carpet_items_extra SET `price_standard` = '$price_standard', `price_daily_1` = '$price_daily_1', `duration_2` = '$duration_2' WHERE item_id = '$log_id AND item_task = '$task' AND item_barcode = '$barcode'");
$update->execute();
}
The problem is when the data is only from the first isset it's saved as it should be, but when there's data in the second isset as well, only the first row in the table gets update.
How can I differentiate between the two?
I have tried using for to execute the query once for every $barcode item, as well as using nested foreach.
The result though was multiple extra entries in the database table.

php loop adds extra data to database

I have loop to store my data and it multiple the rows.
example
I have 3 rows with value of test1 and I need to add this rows to become 5
so I have 3 rows already
I add number in input field 2
I loop this 2 number and create new rows
previously 3 rows + 2 new rows = 5 rows in total
but currently I am getting 9 rows.
Code
foreach($request->input('barcodes') as $bb)
{
for ($i = 0; $i < $request->input('nonuiqueAmount'); ++$i) {
$barcode = new Barcode;
$barcode->product_id = $product->id;
$barcode->returned = false;
$barcode->serial_number = $bb['serial_number'];
$barcode->save();
}
}
In case you need a full code with logic here I shared it for you.
Any idea why I get more than my desire rows?
Solved
Thanks to u_mulder suggestion here is how I solved my issue
foreach($request->input('barcodes') as $bb)
{
$bbb = $bb['serial_number']; // added to get single serial number
}
for ($i = 0; $i < $request->input('nonuiqueAmount'); ++$i) {
$barcode = new Barcode;
$barcode->product_id = $product->id;
$barcode->returned = false;
$barcode->serial_number = $bbb; // changed
if($barcode->save()) {
$user = Auth::user();
$outlets = $user->outlets;
foreach($outlets as $outlet) {
DB::table('outlet_products')->insert([
'outlet_id' => $outlet->id,
'barcode_id' => $barcode->id,
'created_at' => now(),
'updated_at' => now(),
]);
}
}
}

check value for multiple array in loop

i have three array sure[],maybe[] and notify[] that are displaying in a loop like this:
sure[0] maybe[0] notify[0]
sure[1] maybe[1] notify[1]
sure[2] maybe[2] notify[2]
sure[3] maybe[3] notify[3]
And so on...
Now what I want that is in form post I get all arrays and there should be minimum one value of sure[0] or maybe[0] or notify[0] true or checked means horizontally`.
In this process will be same for all next rows and each row must contain minimum one true or checked value although can all selected or checked.
I am trying to solve this problem from past three days .
How can I do this please check it and give me idea.
thanks in advance
You can check whether at least one of the three is set by doing this:
$oneSet = $sure[0] || $maybe[0] || $notify[0];
If you want to do this in a loop, you can do something like this (assuming each list is equally long)
$oneSetInEach = true;
for( $i = 0 ; $i < count($sure) ; $i++ ) {
$thisSet = $sure[$i] || $maybe[$i] || $notify[$i]; // check if one is set here
$oneSetInEach = $oneSetInEach && $thisSet; // if all the previous ones are ok, and this is ok, we are still ok
}
// $oneSetInEach will now be true or false depending on whether each row has at least 1 element set.
If all array count() are same
<?php
$i = 0;
while ($i < count($sure)) {
if ((isset($sure[$i]) AND $sure[$i] == true) OR ( isset($maybe[$i]) AND $maybe[$i] == true) OR ( isset($notify[$i]) AND $notify[$i] == true)) {
// your code
}
$i++;
}
?>
Maybe:
$res = true;
for( $i=0 ; $i<count($sure) ; $i++ ) {
$res &= $sure[$i] || $maybe[$i] || $notify[$i];
}

Saving multiple HTML textareas in CodeIgniter

I would like to grab the values of several textarea fields and save them to the database. For now I have four of each with different values and I want to batch save these values, the textarea fields are:
<textarea name="compedia[]"></textarea>
<textarea name="specification[]"></textarea>
and the save function:
function saveCOA(){
$labref=$this->uri->segment(3);
$data= $this->input->post('compedia');
$data1= $this->input->post('specification');
$compedia=array(
'labref'=>$labref, //NDQA201303001
'compedia'=>$data,
'specification'=>$data1
);
foreach ($compedia as $value) {
$this->db->insert('coa_body',$value);
}
}
When I print_r($value) it returns :
NDQA201303001
Array ( [0] => Alphy [1] => poxy [2] => alphy [3] => poxy )
Array ( [0] => poxy [1] => alphy [2] => poxy [3] => alphy )
and when I try to save, it returns:
A Database Error Occurred
Error Number: 1054
Unknown column 'NDQA201303001' in 'field list'
INSERT INTO `coa_body` (`NDQA201303001`) VALUES ('')
Filename: C:\xampp\htdocs\NQCL\system\database\DB_driver.php
Line Number: 330
How should the syntax be so as to loop over all the textarea values and save them to the database at once?
I hope that
count($data) == count($data1); //Always True!
If that's the case the following will work:
for ($i=0;$i<count($data);$i++) {
$insert_data = array(
'labref'=>$labref, //NDQA201303001 - Same for all the rows
'compedia'=>$data[$i],
'specification'=>$data1[$i]
);
$this->db->insert('coa_body',$insert_data);
}
Check this Link: CodePad.org
Update:
Suggested by Rcpayan:
//This will reduce number of context switching,
//even though loping is doubled!
for ($i=0;$i<count($data);$i++) {
$insert_data[$i] = array(
'labref'=>$labref, //NDQA201303001
'compedia'=>$data[$i],
'specification'=>$data1[$i]
);
}
$this->db->insert_batch('coa_body',$insert_data);
You could do something like this, it's a bit longer but can also deal with compedia and specification not being equal. This solutions assumes a few things:
You want the value of labref to be the same for each row inserted
If the number of values for compedia and specification aren't equal, you still want to insert the row, but the 'missing' values will be set to NULL.
$labref = $this->uri->segment(3);
$compedia_data = $this->input->post('compedia');
$specification_data = $this->input->post('specification');
//Calculate which array is larger, so we can loop through all values
$max_array_size = max(count($compedia_data), count($specification_data));
//Iterate through the arrays
for ($i = 0; $i < $max_array_size; $i++)
{
$this->db->set('labref', $labref);
//If we still have a value(s) for compedia, then assign the value, otherwise set to NULL
if array_key_exists($i, $compedia_data)
{
$this->db->set('compedia', $compedia_data[$i]);
}
else
{
$this->db->set('compedia', NULL);
}
//If we still have a value(s) for specification, then assign the value, otherwise set to NULL
if array_key_exists($i, $specification_data)
{
$this->db->set('specification', $specification_data[$i]);
}
else
{
$this->db->set('specification', NULL);
}
//Insert into table: 'coa_body'
$this->db->insert('coa_body');
}
Alternatively, you could change the loop to assign the values to an array, then batch insert these values. This might offer better performance.
//Initial other relevant code is included in the example above (excluded here for brevity)
$insert_array = new array();
//Iterate through the arrays
for ($i = 0; $i < $max_array_size; $i++)
{
$row_array = new array();
$row_array['labref'] = $labref;
//If we still have a value(s) for compedia, then assign the value, otherwise set to NULL
if array_key_exists($i, $compedia_data)
{
$row_array['compedia'] = $compedia_data[$i];
}
else
{
$row_array['compedia'] = NULL;
}
//If we still have a value(s) for specification, then assign the value, otherwise set to NULL
if array_key_exists($i, $specification_data)
{
$row_array['specification'] = $specification_data[$i];
}
else
{
$row_array['specification'] = NULL;
}
//Add current row to the insert array, so it can be added to the database
$insert_array[$i] = $row_array;
}
//Insert into table: 'coa_body'
$this->db->insert_batch('coa_body', $insert_array);

Algorithm in finding valid and non-duplicate entries in php

I am currently using php to help me find the valide and non-duplicated entry,
which i need
a list of valid and non-duplicated
entry a list of invalid input (unique)
a list of duplicate input
My approach is first create 5 array 2 for orginal ,1 for no mistake (empty),
1 for valid (empty) , 1 for duplicate (empty)
First using one of orginal array, for each one element : check valid
and check duplicate, if invalid , put into invalid array , and check duplicate by using inarray
after all, i get one array of invalid and duplicate , then using the orginal array, check which element is not in that two array. And job done.
My problem is, it seems quite inefficiency, how can i improve it? (Perferable if using some famous algorithm)
Thank you.
// get all duplicate input and store in an array
for ($row = 1; $row <= $highestRow; $row++) {
for ($y = 0; $y < $highestColumn; $y++) {
$val = $sheet->getCellByColumnAndRow($y, $row)->getValue();
//use reg exp to check whether it is valid
if ($y == $mailColumn && !preg_match($pattern,$val))
{$invaild[]=$row;}
//if valid, test whether it is duplicate
elseif ($y == $mailColumn && in_array($val,$email))
{$duplicate[]=$val;
$duplicate[]=$row;}
if ($y == $mailColumn)
{$email[]=$val;
$email=array_unique($email);}
}
}
// unique invalid array since i just need invalid inputs, not the invalid + duplicate input
$invaild=array_unique($invaild);
try this:
<?php
echo "<pre>";
$array1 = array("a#b.com","c","c","d#e.com","test1","","test3","test2","test3");
$array_no_mistake = array_filter($array1,function($subject){if(trim($subject)=="") return true;});
$array_uniq = array_diff(array_unique($array1),$array_no_mistake);
$array_dups = array_diff_assoc(array_diff($array1,$array_no_mistake),$array_uniq);
$array_valid = array_filter($array_uniq,function($subject){
if (preg_match('/\A(?:[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z/i', $subject)) {
return true;
} else {
return false;
}
});
$array_invalid = array_diff_assoc($array_uniq,$array_valid);
print_r($array1);
print_r($array_no_mistake);
print_r($array_uniq);
print_r($array_dups);
print_r($array_valid);
print_r($array_invalid);
?>
1) It would seem you are only interested in the email columns so i think there is no point in iterating over all of the other columns (so the inner loop is basically redundant).
2) You can use associative arrays in order to store emails as indexes and later on efficiently look for duplicates by checking for the existence of the index/email in the array.
Here's an example:
$valid = array();
$invalid = array();
$dups = array();
for ( $row = 0; $row < $highestRow; $row++ )
{
$email = $sheet->getCellByColumnAndRow( $mailColumn, $row )->getValue();
if ( !preg_match( $pattern, $email ) )
{
$invalid[] = $row;
}
else if ( isset( $dups[ $email ] ) )
{
$dups[ $email ][] = $row;
}
else
{
$dups[ $email ] = array();
$valid[] = $row
}
}
At the end of this, $invalid will hold a list of all of the invalid rows, $dups will hold an array of arrays, each indicating the rows in which the current email is the index and its value is an array which lists the rows that share this email. If the array at a certain index is empty, the email is not duplicated.
$valid will hold the numbers of the valid rows.
Now fancy algorithm, sorry...

Categories