mysql update - skip blank fields? - php

I need to know the proper way of doing this.
I have a form where someone can fill in 3 different inputs to update their data.
they can leave one blank if they want and just update the other two or just one. Whatever.
so if i update as:
mysql_query("UPDATE table SET field1=input AND field2=BLANK AND filed3=input WHERE ID=123);
will it leave the blank fields unchanged? just skip over them? or will it replace the field with an empty string/blank field?
If this is the wrong way, what is the correct method?
Thank You!

It will replace them with blank values. The correct way to do it is not to put those items in the query at
all:
if (empty($field1) && empty($field2) && empty($field3) {
// show error message, nothing to do
return;
}
$updates = array();
if (!empty($field1))
$updates[] = 'field1="'.mysql_real_escape_string($field1).'"';
if (!empty($field2))
$updates[] = 'field2="'.mysql_real_escape_string($field2).'"';
if (!empty($field3))
$updates[] = 'field3="'.mysql_real_escape_string($field3).'"';
$updates = implode(', ', $updates);
mysql_query("UPDATE table SET $updates WHERE ID=123");
Obviously it would be cleaner to put the changes in an associative array or object, and then loop through them.

The following UPDATE statement should leave the fields unchanged if the user uses '' as their input, otherwise, it will use the input given to update the field.
UPDATE table
SET field1 = CASE
WHEN input = '' THEN field1
ELSE input
END
, field2 = CASE
WHEN input2 = '' THEN field2
ELSE input2
END
, field3 = CASE
WHEN input3 = '' THEN field3
ELSE input3
END
WHERE ID = 123
This is done with the CASE statement. The WHEN conditions check to see what the input it, and if it is '' (omitted basically) it will use the current value of field1 to update field1 with, basically leaving it unchanged. If there is a value, it will use that new value instead.

If you do not wish to update a certain field you will have to remove the field from your UPDATE statement.
UPDATE table
SET field1=input AND filed3=input
WHERE ID=123

Related

How to get the value of item POST in JForm after submit?

I am currently constructing a component in Joomla and I have to get the values of the form field that user submitted. After that, I have to insert the values into database. The problem is that I just able to insert the $inventory_id but I can't get the value of the form field. Thank you.
<?php
$input = JFactory::getApplication()->input;
$formData = new JRegistry($input->get('jform', '', 'array'));
$name = $formData->get('inventory_name', 'test');
$leadtime = $formData->get('leadtime', null);
$max_lead = $formData->get('max_lead', null);
$daily_usage = $formData->get('daily_usage', null);
$max_usage = $formData->get('max_usage', null);
//formula to calculate reorder point
$lead_time_demand = $leadtime * $daily_usage;
$safety_stock = ($max_usage * $max_lead) - ($daily_usage * $leadtime);
$reorder_point = $lead_time_demand + $safety_stock;
if (empty($this->item->id)){ //For new added item
$inventory_id = $row['AUTO_INCREMENT'];
$sql_new = "INSERT INTO wer_reorder_point_list (inventory_id, inventory_name, reorder_point)
VALUES ('$inventory_id', '$name', '$reorder_point');";
mysqli_query($con,$sql_new);
}
?>
You never declare $row in this code, so what is $inventory_id = $row['AUTO_INCREMENT']; supposed to do?
If your database is configured to autoincrement inventory_id, then you don't need that column in the insert statement. So you could do this:
$sql_new = "INSERT INTO wer_reorder_point_list (inventory_name, reorder_point)
VALUES ('$name', '$reorder_point');";
and it will automatically fill that column with the next integer.
By the way, you should also use prepared statements, especially since you have user input, which could be a security problem.
You don't insert an autoincremented id directly using the form data, you let the database take care of that. If you tried to insert it you could easily end up with a race condition given that in a web application such as Joomla there could be many users attempting to insert new lines with the same id at the same time. This is why your form does not contain an inventory_id value.
If you want to pass a hidden ( from the user) value to the POST you need to include a hidden field with that value in your form. However, as stated in the first paragraph, you would not use that for a unique ID.

Ignore null values on MYSQL query

I have a form for users to enter some information. After the form being submitted, it should query a database with the values that the user entered.
My problem here is that if some of the values that the user entered are null, it should remove from the query.
This is my code:
if(isset($_POST['submit']))
{
include("../includes/header.php");
include ("../scripts/db/connect.php");
//Gets variables from $_POST
$negocio = $_POST['negocio'];
$imovel = $_POST['imovel'];
$distrito = $_POST['distrito'];
$concelho = $_POST['concelho'];
$freguesia = $_POST['freguesia'];
$query = "SELECT * FROM imoveis WHERE negocio = $negocio and imovel = $imovel and distrito = $distrito and concelho = $concelho and freguesia = $freguesia";
}
Imagine if $negocio, $imovel, $concelho and $freguesia are equal to null, the query should be:
$query = "SELECT * FROM imoveis WHERE distrito = $distrito;
How can I do this?
Generate your query string dynamcilly depending on which value are set
or not null, and than use that query
Run this code in a seperate file you will understand the point, after removing or adding comment to any variable, ($name,$street, $address or $qualification )
// you will see query will change depending on the set variable,
//I am using these name you can use any name for your variable
$name='my name';
//$address='some where on earth';
$street='this is my street';
//$qualification='i am very much qualified';
//now create the array only with the values which are not empty or not nul,
//I am using empty you can use null if you want with this example you can use any thing.
if(!empty($name)) $query_string_second_part[]=" AND name = '$name'";
if(!empty($address)) $query_string_second_part[]=" AND address = '$address'";
if(!empty($street)) $query_string_second_part[]=" AND street = '$street'";
if(!empty($qualification)) $query_string_second_part[]=" AND qualification = '$qualification'";
//hand type the first part for the query
$query_string_First_Part= "SELECT * FROM myTableName WHERE";
//Implode the array, if you want to see how it look like use echo,
$query_string_second_part= implode(" ", $query_string_second_part);
//as you can see we are adding AND with every value, so we need to remove the first AND
//with one space
//Make sure you give space in the second parameter. else it wont work means "" not correct but " " is correct
//Hint --> use one space in between the double qoutes
$query_string_second_part= preg_replace("/AND/", " ", $query_string_second_part, 1);
//Join the first and second part together to create a full query
$query_string=$query_string_First_Part.$query_string_second_part;
echo ($query_string);//see how our query look like at the moment
You can add an input null check to each clause. So for example where you do this:
distrito = $distrito
You might instead do this:
(distrito = $distrito or $distrito IS NULL)
or perhaps:
(distrito = $distrito or $distrito = '')
Depending on the data types, the actual input being used to build the query, etc. Might take some tweaking and debugging when manually building a query like this (I suspect using prepared statements with query parameters will make this cleaner, as well as more secure), but the idea is the same either way.
Basically you're instructing it to match the row based on the value, or match the row based on the lack of value. So for any given clause, if the supplied value is null/empty, then all rows match and the clause becomes moot.

how to use a specific UPDATE query if existing row is empty mysql

I have searched far and wide for a specific case were i could get this answer but what i have seems to me like it should work. but it doesn't.
I basically want to concatenate data into a row in my database. Put simply if there is no existing data it injects the filenames variable into the row.
If there is existing data in the row i need to append a "," to the start so that i can break the filenames out later with php on my page.
Here's what i have that doesn't seem to work.
$query = "UPDATE plan
SET plan_files = if(plan_files is null,concat(plan_files,
'{$filenames}'),concat(plan_files, ',{$filenames}'))
WHERE plan_id='{$planid}'";
try this
$query = "update plan SET plan_files = (case when plan_files IS NULL then '".$filenames."' else concat(plan_files , ',".$filenames."') end ) where plan_id =". $planid;
Please make sure that $filenames is string and $planid is int.
You can do like this :
"UPDATE `plan` SET
plan_files=CASE
WHEN (plan_files='') THEN '".$filenames."'
ELSE concat(name,',".$filenames."')
END
WHERE plan_id='".$planid."'"

How does this sql IF statement work?

Im trying to create a php page where logged in users can update their profile.
Ive found an example Im trying to stick to:
I receive the POST from the update form:
$id=$_SESSION['id'];
$info1=mysql_real_escape_string($_POST['info1']);
$info2=mysql_real_escape_string($_POST['info2']);
$info3=mysql_real_escape_string($_POST['info3']);
The sql query to update the profile
$query=mysqli->query("UPDATE profiles SET
info1=IF('$info1' = '', info1, '$info1'),
info2=IF('$info2' = '', info2, '$info2'),
info3=IF('$info3' = '', info3, '$info3')
WHERE id='$id'");
How does this short IF statement work?
I dont want to update the column if there is no input - is that what it does?
How would i add some criteria to the inputs? like length of the string etc.
So, to clarify from Benio's answer which explains the IF() condition, in effect it is saying that for each column you are trying to update,
if the incoming $variable value is blank, replace the column with what it already had (ie: to not destroy it just because a blank value came in). If there IS something other than blank (the other half of the IF() function), update the column with what the $variable is...
and obviously you have 3 different $ variables for each column of info1, 2, 3.
IF(CONDITION, STATEMENT if CONDITION is true) for 2 arguments
IF(CONDITION, STATEMENT if CONDITION is true, STATEMENT if CONDITION is false) for 3 arguments
$sql = sprintf('UPDATE %s SET', $table);
$rowdata = null;
foreach ($rows as $field => $value) {
$rowdata[] = sprintf('%s = %s', $field, $value); // Escape the $value here!
}
$sql .= sprintf(' %s', implode(', ', $rowdata));
So enter your table name in $table and the data that you want to add as key-pair values in an associative array called $rows and you will end up with your query in $sql

Check form fields and insert value to database

I have a simple php/html form wich inserts data to my mysql database.
I have a column on my database called type.
When a form is submitted with various values I want to be able to check the value of those submitted fields and add a value to the column type based on those values:
If the submitted form field field1 has the value value1 and field field2 has the value value2 then insert value3 to column type on my database.
You can manage this with code, if I understand your question right.
Remember, it is a good idea to check the post values, before insert or update some values in the database.
I am using post for the form method, if you use get, replace $_POST with $_GET
<?php
if ($_POST["field1"] == "value1" AND $_POST["field2"] =="value2")
{ $type = $value3
}
else
{ /// create some defaultvalue if the condition is not true.
$type = "youdefaultvalue"
// or you use some other value from your form, for example $_POST["field3"]
}
// here create your sql-action like "insert into ... " or update ....
I am not sure whether you need this exactly. But after reading your question, i hope you are looking like this only.
if($_POST['field1'] == "value1" && $_POST['field2'] == 'value2' ){
// INSERT field3 to type
}

Categories