Send only filled inputs values to database via SQL - php

I have dozens of inputs in an HTML table one can use to enter numerical values. When submit button is pressed all inputs values are added to their corresponding column in the SQL table via post method. Value of <input name="A1> will be sent to column A1 in SQL table, <input name="A2> to column A2, and so on.
I'm currently using something like this (but with dozens of parameters) to insert data in my table :
$sql = "INSERT INTO all_stats_table (A1, A2, A3) VALUES ($A1, $A2, $A3)";
Problem with this approach is that every input needs to be filled or it will result in an SQL error. I initially used php to set all empty inputs value to 0 before sending everything to database, but I don't think this method is the most efficient way to go.
I would rather like to dynamically check which inputs are actually filled and only send their values to the table instead of converting every empty input value to 0 and having to send everything to the database.
I've already set all default values to 0 in SQL, but I don't know how to only send filled input values via SQL. I tried using a php foreach loop but I'm definitely having trouble finding the right SQL syntax.
Is what I'm trying to do possible ? If not, what would be the best practice to make this process more efficient ?
Thank you for your help
EDIT : attempt to adapt akash raigade's great solution to non-numbered SQL columns :
HTML :
<input name='name'>
<input name='address'>
<input name='age'>
PHP :
$Field_list = array ('name','address','age');
$field_string = '';
$input_string = '';
foreach ($_POST as $userInfo=>$userInfo_value) {
if (isset($userInfo)) {
if ($field_string == '') {
$field_string = $field_string.$userInfo; //problem here ?
$input_string = $userInfo_value; //problem here ?
}
else {
$field_string = $field_string.','.$userInfo; //problem here ?
$input_string = $input_string.','.$userInfo_value; //problem here ?
}
}
}
$sql = "INSERT INTO protocole_test (".$field_string.") VALUES (".$input_string.")";
echo $sql ; //check query formed

[Upgraded version]
Basic idea is that we keep NAME attribute of INPUT same as table column-name where it is gonna be stored.Then with help of input tag name and value which are filled we prepare SQL statement which have only required (FILLED) columns and values.
For given example consider following MYSQL table :
sr.no.|name|age|gender
CODE [Tested]:
<input name="name" >
<input name="age" >
<input name="gender" >
<input type='submit'>
<?php
$field_string ='';
$input_string='';
foreach ($_POST as $userInfo=>$userInfo_value){
if($userInfo_value !=''){
echo $userInfo."->".$userInfo_value;
if ($field_string == '') {
$field_string = $field_string.$userInfo;
$input_string = $userInfo_value;
}
else {
$field_string = $field_string.','.$userInfo;
$input_string = $input_string.','.$userInfo_value;
}
}
}
$sql = "INSERT INTO protocole_test (".$field_string.") VALUES (".$input_string.")";
echo $sql ; //check query formed
?>
[original answer]Have a look at following code :
<input name='a1' id='input_for_name'>
<input name='a2' id='input_for_class'>
<input name='a3' id='input_for_seat.no'>
.
.
<input name='an' id='input_for_n'>
Now
<?php
//you must be having field list to be inserted i.e
//INSERT INTO all_stats_table >>>(A1, A2, A3)<<< VALUES ($A1, $A2, $A3)
//A1,A2,A3 is field list here
//so save them into an array.
$Field_list = array ('A1','A2','A3',.......'An');
//Now get which input_field is inputted by :
$i=0;
$field_string = '';
$input_string = '';
for($i<n){
if(isset($_POST['a'.$i])){
if ($field_string == ''){
$field_string = $field_string.$Field_list[$i];
$input_string = $_POST['a'.$i];
}
else {
$field_string = $field_string.','.$Field_list[$i];
$input_string = $input_string.','.$_POST['a'$i];
}}}
$sql = "INSERT INTO (".$field_string.") VALUES (".$input_string.")";
//to check query formed
echo $sql ;
?>
Explanation :
We check which input field is FILLED , if it is field we add its FIELD into FIELD LIST and ITS VALUE in INPUT LIST finally we GENERATE SQL STATEMENT.

Just check if they are not defined or empty, and if so, define them.
if ( (!isset($_POST['A1'])) || (empty($_POST['A1']) ){
$A1 = '0';
} else {
$A1 = $_POST['A1'];
}

I'm not able to test this and it may need some debugging, but you could create a function, then call the function for each input. Something like...
function chkinput($input){
if ( (!isset($_POST[$input])) || (empty($_POST[$input]) ){
$$input = '0';
} else {
$$input = $_POST[$input];
}
return $$input;
}
// You could potentially loop through the post array
// but here I just call the function once per input
chkinput('A1');
chkinput('A2');
...
chkinput('A12');

You loop through the $_POST array and check if it has a value. If it does concatenate it to an variable. Like this:
$fields = "";
$values = "";
foreach($_POST as $key=>$value){
if($value != ''){
if($value != end($_POST)){
$fields .= $key . ", ";
$values .= "'" . $value . "', ";
}else{
$fields .= $key;
$values .= "'" . $value . "'" ;
}
}
}
$sql = INSERT INTO protocole_test ($fields) VALUES ($values) ;
Your SQL would look like :
INSERT INTO protocole_test (A1, A2, A3) VALUES ('A1', 'A2', 'A3')

Related

Inserting form values in multiple row using php empty fields

I need a little help. I have the following code. I wish that when all fields are not completed, not to introduce the empty fields in the database. Just upload the completed them.
for($i = 0; $i <count($_POST)+3; $i++){
mysql_query("INSERT INTO `predare`(`id_factura`,`id_student`, `id_produs`, `cantitate`)
VALUES('".$_POST['id_factura'][$i]."','".$_POST['id_student'][$i]."', '".$_POST['id_produs'][$i]."', '".$_POST['cantitate'][$i]."');");
}
<input class="input-1" name="cantitate[]" id="cantitate" value="">
<input class="input-1" name="id_factura[]" id="id_factura" value="">
<input class="input-1" name="id_student[]" id="id_student" value="">
<input class="input-1" name="id_produs[]" id="id_produs" value="">
Here's how I would suggest doing it. First initialize your SQL string and a separator (for inserting multiple records with one query.)
$sql = "INSERT INTO `predare` (`id_factura`,`id_student`, `id_produs`, `cantitate`) VALUES ";
$separator = '';
Then loop over the submitted rows and append to the SQL string if the rows have all four values.
for ($i = 0; $i < count($_POST['cantitate']); $i++) {
$values = array();
foreach (array('id_factura', 'id_student', 'id_produs', 'cantitate') as $column) {
// only add values to the $values array if something has been entered
// (empty fields will be present as '', which evaluates to false)
if ($_POST[$column][$i]) $values[] = $_POST[$column][$i];
}
if (count($values) == 4) { // only add the values to the SQL if all fields are present
$sql .= "$separator ('" . implode("','", $values) . "')";
$separator = ',';
}
}
Then you can execute the SQL statement to insert all the complete records at once.
If you wanted to include incomplete (but not empty) rows, you could use
if ($values) {... instead of if (count($values) == 4) {...
One benefit to setting it up this way is that it would be easier to convert the code to use a better database extension (such as PDO) with prepared statements instead of concatenating the values into the SQL like this.
You need to go through the $_POST['id_factura'] array and You need to check the values before the insert statement like this:
for($i = 0; $i <count($_POST['id_factura']); $i++){
if(isset($_POST['id_factura'][$i]) && isset($_POST['id_student'][$i]) && isset($_POST['id_produs'][$i]) && isset($_POST['cantitate'][$i])){
mysql_query("INSERT INTO `predare`(`id_factura`,`id_student`, `id_produs`, `cantitate`)
VALUES('".$_POST['id_factura'][$i]."','".$_POST['id_student'][$i]."', '".$_POST['id_produs'][$i]."', '".$_POST['cantitate'][$i]."');");
}
}
Or you can check if the integer values are greater then 0...

How to block inserting empty strings in MySQL

I have this update statement (PHP code):
$sql1="UPDATE `utilizatori` " .
"SET utilizator='$utilizator', parola='$parola1', nume='$nume', " .
"`prenume='$prenume', varsta='$varsta', localitate='$localitate'` ";
WHERE parola='".$_SESSION['parola']."'";
This will update some MySQL table fields via an html form. The user wants to change just his name for instance. He completes just name field, then he presses submit. The data is sent into the table with the UPDATE statement above.
The problem is that it also updates the table with blank values that user didn't complete. I don't want the blank values to be added.
How can I block the blank values to be sent into the table?
If you really wanted to do this in the update, you can change the set statement to something like:
set utilizator = (case when '$utilizator' <> '' then '$utilizator' else utilizator end),
. . .
This will use the previous value if the new one is blank.
You can also do this at the application level by just updating the fields that have changed.
And, you should use parameterized queries rather than directly substituting values into a string. That is another issue, though.
You can do two things to solve this issue. One is to preload the data in the form. So when the user change his name, the other fields are already loaded with the original information.
The second option is to create an update query based on the fields have a value.
Example of option 1:
<?php
//
//GET THE DATA FROM A SELECT QUERY HERE
//FOR EXAMPLE: $sql = "SELECT * FROM `utilizatori` WHERE parola='".$_SESSION['parola']."'";
//Put the data of the sql row in a variable e.g. $sqlRow.
?>
<!--Use variable in your form!-->
<form>
...
...
<input name="nume" value="<?=$sqlRow['nume']?>"/>
<input name="utilizator" value="<?=$sqlRow['utilizator']?>"/>
...
...
</form>
Example of option 2:
<?php
//Catch post data
if($_POST)
{
$updateString = "";
foreach($_POST as $inputField => $inputValue)
{
if($inputValue != "")
{
$updateString .= $inputField." = '".$utilizator."',";
}
}
//Strip last ,
$updateString = substr($updateString,0,-1);
if($updateString != "")
{
//Your query would be
$sql1 = "UPDATE `utilizatori` SET ".$updateString." WHERE parola='".$_SESSION['parola']."'";
}
}
?>
$updateClauseArr = Array();
foreach($_REQUEST as $key => $val){
if(is_numeric($val)){
$updateClauseArr[] = '$key = '.(int) $val;
}else{
$updateClauseArr[] = "$key = '".htmlentities($val,ENT_QUOTES,'UTF-8')."'";
}
}
if(sizeof($updateClauseArr) > 0){
$updateSet = implode(',' ,$updateClauseArr);
$sql1="UPDATE `utilizatori` SET ".$updateSet." WHERE parola='".$_SESSION['parola']."'";
}
See what field values have been submitted by the user. then iterate in a loop for the fields that have value to make variable to be concatenated to the update query.

PHP Select all variables which are equal to 1

I am trying to get an SQL-query to be dynamic.
These are the steps I'm taking:
Step 1:
//Here the user sets which table fields will be used:
<input type="checkbox" name="id" value="1"> ID
<input type="checkbox" name="name" value="1"> name
<input type="checkbox" name="email" value="1"> email
Step 2:
//Here I see what fields the user wants to use and set a variable to 1
<?php
if (isset($_POST['id']) && $_POST['id'] == "1")
{
$form_id='1';
}
//etc etc
?>
Step 3:
//And finally here's the sql query
$sql = mysql_query("select * from mytable");
Now I need to set the fields that the user selected to the query.
For example if the user checks only id and name, then it should look like this:
$sql = mysql_query("select id, name from $table");
What's the best way of doing this?
Why not instead push all of the field names into an array instead of setting disparate variables?
$fields = [];
if(isset($_POST['id']) && $_POST['id'] == 1) {
$fields[] = 'id';
}
Then you should just be able to implode the array together in order to get your select columns:
$fields = implode(', ', $fields);
Also, #h2ooooo is correct, please avoid using mysql_ functions. They are depracated and will be removed in future versions of PHP.
Simply you can use ! empty() function instead of isset() && $_post['id']==1
$select_fields = array();
if(!empty($_POST['id']))
$select_fields[] = 'id';
if(!empty($_POST['name']))
$select_fields[] = 'name';
if(!empty($_POST['email']))
$select_fields[] = 'email';
$query_fields = implode(', ', $select_fields);
$sql = mysql_query("select $query_fields from $table");
The basic solution is to check which parameters are set and equal to one and push the column name into an array if that's the case.
You can then loop through the array and concatenate the fields to the query, making it dynamic.
The biggest concern here is that you're using mysql_* functions which are deprecated. I recommend using PDO since I find them comfortable and handy to use but mysqli is also viable.
With PDO and mysqli you'll be able to use prepared-statements which are the best way to prevent injections so please use them.
Solution
Using the ternary operator, we can check which parameters are set and assign the field names accordingly.
$id = isset($_POST['id']) && $_POST['id'] == 1 ? 'id' : null;
$name = isset($_POST['name']) && $_POST['name'] == 1 ? 'name' : null;
$email = isset($_POST['email']) && $_POST['email'] == 1 ? 'email' : null;
I do this becuse I find the ternary operator prettier than multiple if-statements.
Let's construct an array with the variables that we just created:
$parameters = array($id, $name, $email);
By simply checking which fields are not null we can easily construct the columns array.
$columns = array();
foreach($parameters as $column)
{
if($column != null)
{
$columns[] = $column;
}
}
Finally we can implode the columns together, separating them with a comma:
$activeColumns = implode(",", $columns);
So you can use $activeColumns as a part of your query, which is then recommend to be prepared afterwards.

Update in PDO/SQL with a variable number of variables :)

I have a code that retrieves all the input data sent in a form. If the form had only 2 fields filled out, the PHP gets the value for only those 2 fields (the unchanged fields in the form are not submitted).
Then I would like to UPDATE a SQL table for those fields that I have retrieved with my PHP code. Here is where I am lost. I would need to specify in the SQL only the fields that I have received from the form, but this is variable. Maybe I received only 1 field, maybe I received 7 of the fields...
Here is my code:
if (isset($_POST) && !empty($_POST)) {
echo $internalImage;
foreach ($_POST as $key => $value)
{
echo "Field Name: ".htmlspecialchars($key)." | Value: ".htmlspecialchars($value)."<br>";
}
}
What would you suggest?
You could construct your query like this:
$values=array();
//this will be an array of possible fields that are in your table
$possible=array('field1', 'field2', 'field3');
$i=0;
$len=count($_POST);
$query='update table_name set ';
foreach($_POST as $key => $value){
$k=htmlspecialchars($key);
$v=htmlspecialchars($value);
if(in_array($k, $possible)){
$query .= $k .' = ?'; //placeholder for a value
$values[]=$v; //append values to an array for later use
if($i < ($len-1)) $query .= ', ';
$i++;
}
}
$query .= 'where table_id = ?';
$values[]=$table_id; //forgot that, append id of a row you are to update.
and then prepare and execute the query:
$db->prepare($query);
$db->execute($query, $values);

$_POST as $key => $value using checkboxes

I am having trouble getting a form to update the information passed from a check box. I was given this code.
$one = isset($_POST['one']) ? 'on' : 'off';
This works great as long as I call each check box separately. My problem is I have approximately 200 checkboxes in total.
Here is the code I am using to UPDATE with. Can anyone help me to figure out where to insert the code I was given into my present code? I've tried all sorts of variations.
if($_POST['submit']){
if(!empty($applicant_id)){
$sql = "UPDATE play SET ";
foreach($_POST as $key => $value){
if(($key != 'submit') && ($key != 'applicant_id')){
$sql .= $key. " = '$value',";
}
}
$sql = substr($sql, 0, -1);
$sql .= " WHERE ".$applicant_id." = $applicant_id";
$result = mysql_query($sql,$db) or die(mysql_error(). "<br />SQL: $sql");
}
}
The solution is to start with your known list of possible checkboxes in an array() or similar. Can I assume you generate the form with such a list? If not, you probably should. Then you can use a loop over the same data to check for the existence of each checkbox.
Some other hints:
isset($array[$key]) is not recommended. Although it will be reliable most of the time, it will fail if $array[$key] is null. The correct call is array_key_exists($key, $array).
When assembling string fragments for SQL, like you're doing, it is more elegant to do the following:
$sqlvalues = array();
foreach( $options as $field ) {
if( array_key_exists('checkbox_'.$field, $_POST) )
$sqlvalues[] = $field.' = \'on\'';
else
$sqlvalues[] = $field.' = \'off\'';
}
mysql_query('UPDATE '.$table.' SET '.implode(', ', $sqlvalues).' WHERE applicant_id = '.$applicant_id);
You may be running to HTML checkbox behavior: Checkboxes are only sent to the server if they are on; if they are off, no name/value pair is sent. You are going to have trouble turning off values with the above code.
So you need to run through your known list of values and check for them in the $_POST parameters.
You should use an array name and it will be an array in PHP.
As ndp said, if a checkbox is unchecked, its value will not be transmitted. So you need to use a hidden input field with the same name before the checkbox input field, with the "off" value.
<label for="one">One</label>
<input type="hidden" name="checkboxes[one]" value="off"/>
<input type="checkbox" name="checkboxes[one]" id="one" value="on"/>
Remember checked="checked" if it should be default to on.
You can now loop the checkboxes with POST or GET
foreach ($_POST['checkboxes'] as $key => $value) {
//something
}
if($_POST['submit']){
if(!empty($applicant_id)){
$sql = "UPDATE play SET ";
foreach($_POST as $key => $value){
if(($key != 'submit') && ($key != 'applicant_id')){
$sql .= $key . " = '" . ($value ? 'on' : 'off') . "',";
}
}
$sql = substr($sql, 0, -1);
$sql .= " WHERE ".$applicant_id." = $applicant_id";
$result = mysql_query($sql,$db) or die(mysql_error(). "<br />SQL: $sql");
}
}
The above assumes that all your inputs are checkboxes. If they aren't, you'll need to work out a convention to distinguish them.
Incidentally, your currently running UPDATE code is vulnerable to SQL injection because you aren't sanitizing your inputs with mysql_real_escape_string(). Cheers.
delete everything above :-)
name all you checkboxes like
and in foreach work with $_POST['out']
BUT! don't forget the golden rule: DOn't belive to the user. re-check every key=>value before writing to the datebase.

Categories