Update INT/DECIMAL field with a null/no value - php

I have a lot of input box's. Each input box is linked with a INT or DECIMAL MySQL field and is displayed inside the text box.
The default value of each INT/DECIMAL is a null so that when a user first opens the page, nothing is shown inside the text box's.
I have an update query that updates the value of each input box to the respected MySQL Field.
My problem is, for each input box that doesn't get anything typed in, the value of the field switches from a NULL to a 0.
I am having trouble figuring out a way to update the un-touched input's to a NULL and not have all my untouched values go to 0. Can anyone help?
Defining my variables basically goes like:
if(nullBlank($_POST['variable1']) == false)
$variable1 = $_POST['variable1'];
else
$variable = "";
I've also tried: $variable = null;
My update query basically looks like this:
mysql_query("UPDATE `table` SET `variable1`= '" . $variable1 . "' WHERE something = something
My nullBlank() function
function nullBlank($data)
{
if(is_null($data))
$value = true;
elseif(strlen($data) <= 0)
$value = true;
elseif($data === "")
$value = true;
else
$value = false;
return $value;
}

Set $variable1 to "NULL" (the string). This way it will end up in the query as NULL, which is what represents NULL in SQL.

Perhaps change your code for null checks to
if (is_null($myVariable)) {
$sql .= "$columnName= NULL";
} else {
$sql .= "$columnName= '" . mysql_real_escape_string($myVariable) . "'";
}
then call this for each value and it will either null it or quote it

Related

PHP Laravel save() is saving even when the condition is false

A null value is value is saved every time the textbox is empty. I need the code to not save anything in the database if the textbox is left empty.
if('questionName'!=''){
$questionName = NEW Question();
$questionName->question_name = request('questionName');
$questionName->user_id = Auth::user()->user_id;
$questionName->save();
$questionid = DB::getPdo()->lastInsertId();
}
elseif('questionName'==''){
$questionid = request('question_id');
}
You are comparing a string i.e 'questionName' with '' that is always true.
Change this
if('questionName'!='')
to
if ($request->input('questionName') != '' )

Variable $newvar5 not being passed in UPDATE statement

I wondered if anyone could shed some light as to why $newvar5 (integer) is not being passed in the UPDATE statement but is if i explicitly declare $newvar5 = 1; for example. If I don't explicitly declare it I can still echo they type and value of $newvar5 and I get integer and 1 (respectively) where the 1 is the value returned from a select dropdown. Thanks
<?php
$newvar3 = $_POST["area1"];
$newvar4 = $_POST['select1'];
$newvar5 = current($newvar4);
settype($newvar5, "integer");
echo $newvar5;
/*
The above echoes $newvar5 = 1 (it's type is integer) when i select the
first value from the select dropdown but it doesn't work in the update
query shown below. However, it does work if i explicitly code $newvar5=1;
*/
if(isset($_POST['button'])) {
$sql = "UPDATE tblContent SET content = '$newvar3' WHERE contentID='$newvar5'";
if ($conn->query($sql) === TRUE) {
echo "<br>";
echo "Updated Successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
?>
Thanks for the replies folks. Yes, I'm aware that it's open to SQL injection. That was on my to do list. For now i just want to be able to update the database. I used current() because, as you correctly inferred, the select values are in array format. I'm still no further forward as to why this isn't working. When i declare $newvar5 = 1; the update works fine yet when i set $newvar5 = current($newvar4); it doesn't (even though it echoes out the same value = 1 and type = integer.

PHP - Change value of variable before inserting into sql - Without Ajax

I have the variable
$sql1 .= "Brukertype";
Which gets information set from an already-filled textbox. It can either have the value Administrator or the value Iskjører.
What is the best way to change these values before inserting them into SQL?
The Administrator value should get changed to the value 1 and Iskjører gets changed to the value 2.
I can't use a select function (dropdown list) on the question because it needs to be enabled/disabled on my command.
This is a reasonable place to use a switch statement. You want a 'marshaling' function, like this:
function marshal_input($input) {
$result = 0;
switch ($input){
case 'Administrator':
$result = 1;
break;
case 'Iskjører':
$result = 2;
break;
case 'SomethingYouHaventThoughtOfYet':
$result = 3;
break;
default:
$result = 0;
break;
}
}
However, the implementation of the marshaling function can be almost anything:
function marshal_input($input) {
$options = array("Administrator" => 1, "Iskjører" =>2);
return $options[$input];
}
The point is that you need some code that maps from the human-readable form to the numerical representation the db needs. Then you just call it like so:
$sql_version = marshal_input($sql1);//Doesn't overwrite the variable
//...or...
$sql1 = marshal_input($sql1);//Note this overwrites the variable.
Since you have stated:
It can eighter have the value "Administrator" or the value "Iskjører"...
we only check whether the value is 'Administrator' or not.
Try this:
$val = 'Administrator'; // user input variable
$sql_val = ($val == 'Administrator') ? 1 : 2;
If value is 'Administrator' set $sql_val to 1, else set $sql_val to 2

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 search/replace empty records in mysql

Trying to do a search and replace using php/mysql. I do this in specified table headers/columns. it works fine when my search term has a value. However i want to search for an empty field in a specified column and replace with a value. it fails to do a search and replace when my search term is an empty string. Any help?
$SearchAndReplace_header = isset($_POST['SearchAndReplace_header']) ? $_POST['SearchAndReplace_header'] : "";
$SearchAndReplace_search_term = isset($_POST['SearchAndReplace_search_term']) ? $_POST['SearchAndReplace_search_term'] : "";
$SearchAndReplace_replace_with = isset($_POST['SearchAndReplace_replace_with']) ? $_POST['SearchAndReplace_replace_with'] : "";
//foreach($fields as $key => $val) {
// if($SearchAndReplace_header == "all" || ($SearchAndReplace_header == $val)) {
// replace column value with parameter value
$sql = "UPDATE ".$table_name." SET ".$val." = REPLACE(".$val.",'".$SearchAndReplace_search_term."','".$SearchAndReplace_replace_with."')";
$db->query($sql);
// }
// }
You can't do a replace on an empty field, you'll have to set the field directly.
UPDATE table
SET column = 'value'
WHERE column = '' or column is null
If you want to cover both cases in a single query, you could do something like this:
UPDATE table
SET column = CASE
WHEN column IS NULL OR COLUMN = ''
THEN 'replace'
ELSE
REPLACE(column, 'find', 'replace')
END CASE

Categories