Insert only populated fields into MySQL - php

im trying to insert only populated ID fields to MySQL, meaning if two out of three are populated, only two to be inserted. I got blind with many code lines, and can't see where Im making a mistake.
Logic is that I'll search for the serial number, once selected it will populate row ID from the serial number into the ID field.
I want to pass ID field value to the database. However, below code is submitting all ID fields even the empty ones (where serial number is not selected), and I dont need to pass records for not populated ID field.
Where am I making a mistake?
Thanks
$idCount = count($_POST['assetsn_id']);
echo $idCount;
for($i=0; $i < $idCount; ++$i) {
$assetsn_id = $_POST['assetsn_id'][$i];
$assetsn_location_address = $_POST['assetsn_location_address'];
$assetsn_location_rack = $_POST['assetsn_location_rack'];
$assetsn_location_shelf = $_POST['assetsn_location_shelf'];
$assetsn_location_bin = $_POST['assetsn_location_bin'];
$assetsn_location_createdby = $_SESSION['user']['id'];
$assetsn_location_userlogid = $_SESSION['user']['userlogid'];
$sql = "INSERT INTO asset_serial_locations SET assetsn_id=?, assetsn_location_address=?, assetsn_location_rack=?, assetsn_location_shelf=?, assetsn_location_bin=?, assetsn_location_createdby=?, assetsn_location_userlogid=?";
$result = modifyRecord($sql, 'sssssss', [$assetsn_id, $assetsn_location_address, $assetsn_location_rack, $assetsn_location_shelf, $assetsn_location_bin, $assetsn_location_createdby, $assetsn_location_userlogid]);
if ($result) {
$_SESSION['success_msg'] = "Location updated successfully!";
header("location: " . BASE_URL . "workshop/location/");
exit(0);
} else {
$_SESSION['error_msg'] = "Something went wrong. Could not update locations.".'<br />'.mysqli_error($conn);
}
}
Serial number #1
<input class="form-control form-control-lg" type="search" name="" autocomplete="off" placeholder="search for serial number..." />
<input class="form-control form-control-lg" type="text" name="assetsn_id[]" autocomplete="off" placeholder="ID" /><br /><br />
Serial number #2
<input class="form-control form-control-lg" type="search" name="" autocomplete="off" placeholder="search for serial number..." />
<input class="form-control form-control-lg" type="text" name="assetsn_id[]" autocomplete="off" placeholder="ID" /><br /><br />
Serial number #3
<input class="form-control form-control-lg" type="search" name="" autocomplete="off" placeholder="search for serial number..." />
<input class="form-control form-control-lg" type="text" name="assetsn_id[]" autocomplete="off" placeholder="ID" />

Use array_filter to remove nulls values from an array :
$_POST['assetsn_id'] = array_filter($_POST['assetsn_id']);
$idCount = count($_POST['assetsn_id']);
echo $idCount;
for($i=0; $i < $idCount; ++$i) {
....
}
Here what array_filter can remove :
$a = array(0, '0', NULL, FALSE, '', array());
var_dump(array_filter($a));
// array()

Related

Php not receiving data from form

I have a excerpt of my form, as follows:
// If logged in shows this box (it's backed behind a include php file that makes the login check
<form action="./saveList.php" method="post" id="ListaComprasForm">
<div class="submitButtonEncap">
<button type="submit" method="POST" name="submitButton" class="btn btn-primary roundedBorder" form="ListaComprasForm" value="submit">
<span class="glyphicon glyphicon-floppy-disk" aria-hidden="true"></span> Save List
</button>
</div>
<input type="text" id="Limpeza0" name="Limpeza[]" class="listInput" autocomplete="off" maxlength="50">
<input type="checkbox" class="x" id="L_chck_0" name="L_chckb_[]" value="check"/>
<input type="text" id="Limpeza1" name="Limpeza[]" class="listInput" autocomplete="off" maxlength="50">
<input type="checkbox" class="x" id="L_chck_1" name="L_chckb_[]" value="check"/>
<input type="text" id="Limpeza2" name="Limpeza[]" class="listInput" autocomplete="off" maxlength="50">
<input type="checkbox" class="x" id="L_chck_2" name="L_chckb_[]" value="check"/>
<input type="text" id="Limpeza3" name="Limpeza[]" class="listInput" autocomplete="off" maxlength="50">
<input type="checkbox" class="x" id="L_chck_3" name="L_chckb_[]" value="check"/>
<input type="text" id="Limpeza4" name="Limpeza[]" class="listInput" autocomplete="off" maxlength="50">
<input type="checkbox" class="x" id="L_chck_4" name="L_chckb_[]" value="check"/>
<input type="text" id="Limpeza5" name="Limpeza[]" class="listInput" autocomplete="off" maxlength="50">
<input type="checkbox" class="x" id="L_chck_5" name="L_chckb_[]" value="check"/>
<input type="text" id="Limpeza6" name="Limpeza[]" class="listInput" autocomplete="off" maxlength="50">
<input type="checkbox" class="x" id="L_chck_6" name="L_chckb_[]" value="check"/>
</form>
This form, on submit, will submit to a DB wether or not checkboxes and TextBox fields have been filled or not. The checkboxes that have been checked or not, he'll submit them over as Y and N or nullo for the Textboxes respectively through some sorting code as follows:
if (isset($_POST['submitButton'])){
$L_chck[] = array();
$H_chck[] = array();
$V_chck[] = array();
$F_chck[] = array();
$Cong_chck[] = array();
$Cons_chck[] = array();
$Outros_chck[] = array();
$Outros = array();
for ($counter = 0; $counter <= 6; $counter++){
$L_chck[$counter] = (isset($_POST['L_checkb_'.$counter]) ? 'Y' : 'N');
$H_chck[$counter] = (isset($_POST['H_checkb_'.$counter]) ? 'Y' : 'N');
$V_chck[$counter] = (isset($_POST['V_chckb_'.$counter]) ? 'Y' : 'N');
$F_chck[$counter] = (isset($_POST['F_chckb_'.$counter]) ? 'Y' : 'N');
$Cong_chck[$counter] = (isset($_POST['Cong_chckb_'.$counter]) ? 'Y' : 'N');
$Cons_chck[$counter] = (isset($_POST['Cons_chckb_'.$counter]) ? 'Y' : 'N');
$Outros_chck[$counter] = (isset($_POST['Outros_chckb_'.$counter]) ? 'Y' : 'N');
if (empty($_POST['Outros'.$counter])) {
$Outros[$counter] = $_POST['Outros'.$counter] = 'nullo';
} else {
$Outros[$counter] = $_POST['Outros'.$counter];
}
}
for ($i=0; $i <= 4; $i++) {
/*if ((isset($_POST['Limpeza'.$i])) == false) {*/
if (empty($_POST['Limpeza'.$i])) {
$Limpeza[$i] = $_POST['Limpeza'.$i] = 'nullo';
} else {
$Limpeza[$i] = $_POST['Limpeza'.$i];
}
if (empty($_POST['Higiene'.$i])) {
$Higiene[$i] = $_POST['Higiene'.$i] = 'nullo';
} else {
$Higiene[$i] = $_POST['Higiene'.$i];
}
if (empty($_POST['Vegetais'.$i])) {
$Vegetais[$i] = $_POST['Vegetais'.$i] = 'nullo';
} else {
$Vegetais[$i] = $_POST['Vegetais'.$i];
}
if (empty($_POST['Fruta'.$i])) {
$Fruta[$i] = $_POST['Fruta'.$i] = 'nullo';
} else {
$Fruta[$i] = $_POST['Fruta'.$i];
}
if (empty($_POST['Congelados'.$i])) {
$Congelados[$i] = $_POST['Congelados'.$i] = 'nullo';
} else {
$Congelados[$i] = $_POST['Congelados'.$i];
}
if (empty($_POST['Conservas'.$i])) {
$Conservas[$i] = $_POST['Conservas'.$i] = 'nullo';
} else {
$Conservas[$i] = $_POST['Conservas'.$i];
}
}
This data is then passed on as arguments to a function to be serialized and sent to DB fields, all of them varchar(255):
savingListData($L_chck, $H_chck, $V_chck, $F_chck, $Cong_chck, $Cons_chck, $Outros_chck, $Limpeza, $Higiene, $Vegetais, $Fruta, $Congelados, $Conservas, $Outros);
So far, every piece of data, being it checked/filled or not, it transposes over to the DB as null. In the case of the checkboxes, N, and in the case of the Textboxes nullo.
I'm led to believe that something is wrong in the sorting but I'm puzzled and can't figure out why. Would really appreciate some help!!
EDIT: Added more of the form in a shortened manner. (It's a big form!)
I think you are trying to retrieving it using wrong name. Its L_chckb_[]
<input type="checkbox" class="x" id="L_chck_0" name="L_chckb_[]" value="check"/>
So you need to use the loop counter outside the name key like this:
$L_chck[$counter] = (isset($_POST['L_chckb_'][$counter]) ? 'Y' : 'N');
The problem is: the name attribute in the tag is L_chckb_ but you are trying to retrieve it by L_checkb_ so that is the issue.
Because L_checkb_ is not set and so it is giving you N.

PHP inserting multiple checkbox AND textbox arrays into MySQL Database

I'm having trouble with the array results in my php. My first problem is this :
It shows everything even if the checkbox isn't checked. My second problem is that it won't insert the values to the database even though it's connected to the database (as you can see in the previous screenshot, it says "connected successfully").
This is my html form:
<form method="POST">
<input type="hidden" name="item[]" value="cupcake">
<input type="text" name="items" value="cupcake" readonly><br>
<b>Price :</b> <span name="price" value="3.00">$17.00</span><br>
Quantity: <input tabindex="1" name="quantity[]" min="0" max="5" type="number" class="quantity" value="1" /><br>
<input tabindex="1" name="checkbox[]" type="checkbox" value="17" /><span>Add to Cart</span></label></div></div></td><br>
<input type="hidden" name="item[]" value="cake">
<input type="text" name="items" value="cake" readonly><br>
<b>Price :</b> <span name="price" value="20.00">$20.00</span><br>
Quantity: <input tabindex="1" name="quantity[]" min="0" max="5" type="number" class="quantity" value="1" /><br>
<input tabindex="1" name="checkbox[]" type="checkbox" value="20" /><span>Add to Cart</span></label></div></div></td><br>
<input type="submit" name="insertBT"><br>
</form>
PHP:
if(isset($_POST['insertBT']))
{
class db_conn
{
public function create_conn($servername, $username, $password, $db)
{
global $conn;
$conn = new mysqli ($servername, $username, $password, $db);
}
public function check_conn()
{
global $conn;
if($conn->connect_error)
{
die ("Connection Failed : " . $conn->connect_error);
}
else
{
echo ("Connected Successfully <br>");
}
}
public function insert()
{
if(isset($_POST['checkbox'])) {
foreach($_POST['checkbox'] as $check) {
$check = implode(',', $_POST['checkbox']);
$name = implode(',', $_POST['item']);
$quantity = implode(',', $_POST['quantity']);
}
echo $check . "<br>";
echo $name . "<br>";
echo $quantity . "<br>";
mysql_query("INSERT INTO purchases(Product, Quantity, Price) VALUES('$name', '$quantity','$check')");
}
}
}
$obj1 = new db_conn;
$obj1->create_conn("localhost","root","", "dbtest");
$obj1->check_conn();
$obj1->insert();
}
You shouldn't be using implode. That puts a comma-separated list of everything in the form into each row that you insert, and repeats this for every box that's checked. You should just insert one item in each row, by indexing the arrays.
However, when you have a checkbox in a form, it only submits the ones that are checked. The result of this is that the indexes of the $_POST['checkbox'] array won't match up with the corresponding $_POST['item'] and $_POST['quantity'] elements. You need to put explicit indexes into the checkbox names so you can relate them.
<form method = "POST">
<input type = "hidden" name = "item[]" value = "cupcake">
<input type = "text" name = "items" value = "cupcake" readonly><br>
<b>Price :</b> <span name = "price" value = "3.00">$17.00</span><br>
Quantity: <input tabindex="1" name="quantity[]" min="0" max="5" type="number" class="quantity" value="1" /><br>
<input tabindex="1" name="checkbox[0]" type="checkbox" value="17" /><span>Add to Cart</span></label></div></div></td><br>
<input type = "hidden" name = "item[]" value = "cake">
<input type = "text" name = "items" value = "cake" readonly><br>
<b>Price :</b> <span name = "price" value = "20.00">$20.00</span><br>
Quantity: <input tabindex="1" name="quantity[]" min="0" max="5" type="number" class="quantity" value="1" /><br>
<input tabindex="1" name="checkbox[1]" type="checkbox" value="20" /><span>Add to Cart</span></label></div></div></td><br>
<input type = "submit" name = "insertBT"><br>
</form>
Then your PHP code can be like this:
$stmt = $conn->prepare("INSERT INTO purchases (Product, Quantity, Price) VALUES (?, ?, ?)");
$stmt->bind_param("sis", $name, $quantity, $price);
foreach ($_POST['checkbox'] as $i => $price) {
$name = $_POST['name'][$i];
$quantity = $_POST['quantity'][$i];
$stmt->execute();
}
BTW, putting the prices in your HTML seems like a bad idea. Nothing stops the user from modifying HTML using the web inspector before they submit the form, so they could lower the price. You should get the prices from the database when processing the form.
Also, notice that in your original code you opened the database connection using MySQLi, but then you tried to do the insert using mysql_query instead of $conn->query(). You can't mix APIs like that; myql_query can only be used when you open the connection with mysql_connect.

Update multiple SQL records using one PHP/MySQLi query

Is it possible to update multiple records in one MySQLi query?
There are 4 records to be updated (1 for each element level) when the submit button is clicked.
The results are posted to a separate PHP page which runs the query and returns the user back to the edit page. elementid is 1,2,3,4 and corresponds with Earth, wind, fire, water. These never change (hence readonly or hidden)
<form id="edituser" name="edituser" method="post" action="applylevelchanges.php">
<fieldset>
<legend>Edit Element Level</legend>
<?php
while($userdetails->fetch())
{?>
<input name="clientid" id="clientid" type="text" size="8" value="<?php echo $clientid; ?>" hidden />
<input name="elementid" id="elementid" type="text" size="8" value="<?php echo $elementid;?>" hidden />
<input name="elemname" id="elemname" type="text" size="15" value="<?php echo $elemname; ?>" readonly />
<input name="elemlevel" id="elemlevel" type="text" size="8" required value="<?php echo $elemlevel; ?>" /></br>
</br>
<?php }?>
</fieldset>
<button type="submit">Edit Student Levels</button>
</form>
And the code to apply the changes
<?php
if (isset($_POST['clientid']) && isset($_POST['elementid']) && isset($_POST['elemname']) && isset($_POST['elemlevel'])) {
$db = createConnection();
$clientid = $_POST['clientid'];
$elementid = $_POST['elementid'];
$elemname = $_POST['elemname'];
$elemlevel = $_POST['elemlevel'];
$updatesql = "update stuelement set elemlevel=? where clientid=? and elementid=?";
$doupdate = $db->prepare($updatesql);
$doupdate->bind_param("iii", $elemlevel, $clientid, $elementid);
$doupdate->execute();
$doupdate->close();
$db->close();
header("location: edituserlevel.php");
exit;
} else {
echo "<p>Some parameters are missing, cannot update database</p>";
}

MySQL/PHP: Insert form array into database?

I am a PHP newbie having a problem inserting an array from a form into the database using foreach statement.
I am trying to create a form that accepts Score, Grade and Comment for each subject. However,only the last subject gets inserted into the database. The list of subjects is loaded from previously registered subjects (I have no problem with that). My problem is getting all the subjects to save back to database.
This is the form i use:
<legend>ENTER RESULTS:</legend>
<input type="hidden" name="results[]" value= "<?php foreach ($subjects as $subject):?>
<ul>
<li> <input type="text" name="subject_name" size="10" value ="<?php htmlout($subject['subject_name']); ?>"/>
</label>
<label for="subject_score">SCORE:</label>
<input type="text" name="subject_score" size="5" value = "<?php
htmlout($subject_score);?>"/> <label for="subject_score">GRADE:</label>
<input type="text" name="subject_grade" size="5" value = "<?php
htmlout($subject_grade);?>"/><label for="subject_grade">COMMENT:</label>
<input type="text" name="subject_comment" size="30" value = "<?php
htmlout($subject_comment);?>"/> </div></li>
<?php endforeach; ?>
<input type="hidden" name="student_id" value="<?php
htmlout($student_id); ?>
</fieldset>
This is the php code i use:
if (isset($_GET['result']))
{
try
{
$sql = 'INSERT INTO results SET
student_id = :student_id,
subject_name = :subject_name,
subject_grade = :subject_score,
subject_grade = :subject_grade,
subject_comment = :subject_comment';
$s = $pdo->prepare($sql);
foreach ($_POST['results'] as $result)
{
$s->bindValue(':student_id',$_POST['student_id']);
$s->bindValue(':subject_name', $_POST['subject_name']);
$s->bindValue(':subject_score', $_POST['subject_score']);
$s->bindValue(':subject_grade', $_POST['subject_grade']);
$s->bindValue(':subject_comment', $_POST['subject_comment']);
$s->execute();
}
}
catch (PDOException $e)
{
$error = 'Could not Register the Student for the Subjects, Please try again'.$e->GetMessage();
include 'error.html.php';
exit();
}
echo 'Success';
you can use form element in array like subject_score[]
your form should be like
foreach
<input type="text" name="subject_name[]" size="10" value ="<?php htmlout($subject['subject_name']); ?>"/>
</label>
<label for="subject_score">SCORE:</label>
<input type="text" name="subject_score[]" size="5" value = "<?php
htmlout($subject_score);?>"/> <label for="subject_score">GRADE:</label>
<input type="text" name="subject_grade[]" size="5" value = "<?php
htmlout($subject_grade);?>"/><label for="subject_grade">COMMENT:</label>
<input type="text" name="subject_comment[]" size="30" value = "<?php
htmlout($subject_comment);?>"/> </div></li>
endforeach
then you can collect those value like below
foreach($_POST['subject_name'] as $key=>$val){
//val will hold subject name
}

Insert array values + single form values into all rows

I am trying to insert values from a form into my mysql database. I have single value forms + array values from the form. How can I insert the array values into my database with the single form values attached to all rows?
The HTML:
Start:<br>
<input type="text" name="start" id="start">
End:<br>
<input type="text" name="end" id="end">
<input type="text" name="item[]" placeholder="Manufacturer #" /><br>
<input type="text" name="description[]" placeholder="Description" /><br>
<input type="text" name="item[]" placeholder="Manufacturer #" /><br>
<input type="text" name="description[]" placeholder="Description" /><br>
<input type="text" name="item[]" placeholder="Manufacturer #" /><br>
<input type="text" name="description[]" placeholder="Description" /><br>
The PHP:
if (isset($_POST['submit']))
{
$link = mysql_connect('localhost', 'user', 'pass');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mydb") or die(mysql_error());
echo 'Connected successfully';
$query = "INSERT INTO agreement (start, end, item_number, item_description) VALUES ";
foreach($_POST['item'] as $i => $item)
{
// Get values from post.
$item = mysql_real_escape_string($item);
$description = mysql_real_escape_string($_POST['description'][$i]);
$start = mysql_real_escape_string($_POST['start'][$i]);
$end = mysql_real_escape_string($_POST['end'][$i]);
// Add to database
$query = $query." ('$start','$end','$item','$description') ,";
}
$query = substr($query,0,-1); //remove last char
$result = mysql_query($query);
}
I will be changing the code to mysqli/pdo, I know that the current code is unsecure.
Any help is appreciated, thanks!
Just use $_POST['start'] and $_POST['end'] without array access since they will be the same each time. You can use array access for item and description.

Categories