SQL update to NULL using a variable - php

I keep having problems with quotes in relation to a table update. I'm sending a Post with several values from a form, and then update a table with them. For the code to work, I need to wrap keys with backslash ($ColumnaString), and values with single quotes ($ValueString). This works OK. My problem is that occasionally I want to update to NULL (when $value==""). But my present code don't do that. Can somebody spot the problem?
$id_tag=trim($_POST['id']);
foreach($_POST as $key=>$value){
if ($key!="UpdatePeople"){
$ColumnaString="`".$key."`";
$ValueString="'".iconv('UTF-8', 'ISO-8859-1//TRANSLIT', utf8_encode($value))."'";
if ($key=="In_Date" and $value=="") {$ValueString==NULL;} //Hereis my problem I think
$link->query("UPDATE MyTable SET ".$ColumnaString."=".$ValueString." WHERE `id`=".$id_tag."");
}
}

You could check $id_tag and create a proper part of sql code
$str = ($id_tag ='' ) ? ' is null ' : ' = '.$id_tag;
$link->query("UPDATE MyTable SET ".$ColumnaString." = ".$ValueString." WHERE `id`".str."");
and for $vale
if ($key=="In_Date" and $value=="") { $ValueString = 'NULL' ;} //Hereis my problem I think

check your database if the columns is defined as NOT NULL

Related

Why does this UPDATE query not update my table?

I am trying to code a user system. I am having an issue with the activation part. I can select and insert data to my table but now I am trying to create an update statement and got stuck.
<?PHP
include "db_settings.php";
$stmt = $dbcon->prepare("UPDATE 'Kullanicilar' SET 'Aktivasyon' = ? WHERE 'KullaniciID'=?");
// execute the query
$stmt->execute(array('1','5'));
// echo a message to say the UPDATE succeeded
echo $stmt->rowCount() . " records UPDATED successfully";
?>
And I am getting error as:
"0 records UPDATED successfully".
This is my table; http://i.imgur.com/PL2eD80.png
I have tried by changing my 'Aktivasyon' type int to char but it also does not work.
EDIT:
I am trying to make this a function;
function dataUpdate($tableName, $updateRow, $updateValue, $conditonRow, $conditionValue)
{
include "db_settings.php";
$q = $dbcon->prepare("UPDATE $tableName SET $updateRow= ? WHERE $conditonRow= ?");
$q->execute(array($updateValue,$conditionValue));
}
I also try this :
...
$q = $dbcon->prepare("UPDATE `$tableName` SET `$updateRow`= ? WHERE `$conditonRow`= ?");
...
How can I make this statement work?
You are using wrong quotes. You are basically saying "update this table, set this string to something when the string KullaniciID equals the string 5" which of course never is true.
You should use backticks ` if you want to specify column names. Then your query would work. Usually you don't even need those, but for some reason MySQL world is always adding them.
So to clarify, this is a string: 'KullaniciID' and this is a column name: `KullaniciID`.
Also you should not send integers as strings. It causes extra conversions or even errors with more strict databases.

How to only update an sql table column if a variable is not empty with php?

I am getting my variables from form fields using php :
$url=$_POST['url'];
$tags=$_POST['tags'];
$skillArea=$_POST['skill_area'];
$description=$_POST['description'];
$slideshowImageFileName=($_FILES['imageNameSlideshow']['name']);
But when I run my sql insert query, I get an error if one of the variables is empty, so I have taken to write if statements to deal with this to rewrite the query string, but surely, that's not the answer? It seems very messy
if(empty($slideshowImageFileName)){
$query1="INSERT INTO portfolio (item_name,image_path,description,url) VALUES('$itemName','$imageFileName','$description','$url')";
}else{
$query1="INSERT INTO portfolio (item_name,image_path,description,url,slideshow_image_path) VALUES('$itemName','$imageFileName','$description','$url','$slideshowImageFileName')";
}
I suppose you are looking for something like this:
$slideshowImageFileName = (isset($_FILES['imageNameSlideshow']['name']) && !empty($_FILES['imageNameSlideshow']['name'])) ? $_FILES['imageNameSlideshow']['name'] : NULL;
This will check if the name of the slideshowimage is set and not empty. if it is NULL will be assigned to the variable, if its correct the value will be assigned.
You could replace NULL with "" if you want an empty string to be added.
Try to set the value of $slideshowImageFileName to empty string or a single space as your database table will accept, and use the second query always.
if(empty($slideshowImageFileName)){
$slideshowImageFileName = "";
}
$query1="INSERT INTO portfolio (item_name,image_path,description,url,slideshow_image_path) VALUES('$itemName','$imageFileName','$description','$url','$slideshowImageFileName')";
I am agreed with Mr. Ray. But there is another solution apart from that. Probably slideshow_image_path field on the table doesn't allow null. So you may change the attribute by allowing null and it will work.
I'd probably construct a builder if I'm sure I'll get a lot of optional data.
Like this:
$acceptedKeys = array
('item_name',
'image_path',
'description',
'url',
'slideshow_image_path');
$inserts = array();
foreach($_GET as $key => $var) {
if(in_array($key, $acceptedKeys)) {
// clean and validate your keys here!
$inserts[$key] = $var;
}
}
$customKeys = implode(array_keys($inserts), ',');
$customValues = implode($inserts, ',');
$query = "INSERT INTO portfolio ($customKeys) VALUES($customValues)";
There's a few options to this.
Simplest one is to make sure the variables are always set, even if not passed through:
//Set up your database connection as normal, check errors etc.
$db = mysqli_connect($host,$user,$password,$db);
$url = isset($_POST['url']) ? mysqli_real_escape_string($db, $_POST['url']) : "";
$tags= isset($_POST['tags']) ? mysqli_real_escape_string($db, $_POST['tags']) : "";
Escaping data is good practice :) In your INSERT query you'll still need to wrap the values in quotes, or you could do that in the above code as per your preference.
http://uk3.php.net/manual/en/mysqli.construct.php

PHP MYSQL - empty variable fails on insert

I have an insert statement that inserts variables collected from a form POST on the previous page. If the variables from the form are not filled in it fails on insert (presumably because it is inserting an empty string...) I have the dataype set to allow NULL values - how do I insert null values if the field was left empty from the form POST?
$query = "
INSERT INTO songs (
userid,
wavURL,
mp3URL,
genre,
songTitle,
BPM
) VALUES (
'$userid',
'$wavFile',
'$mp3File',
'$genre',
'$songTitle',
'$BPM'
)
";
$result = mysql_query($query);
The exact manner depends on if you are writing the query or binding parameters to a prepared statement.
If writing your own, it would look something like this:
$value = empty($_POST['bar']) ? null : $_POST['bar'];
$sql = sprintf('INSERT INTO foo (bar) VALUES (%s)',
$value === null ? 'NULL', "'".mysql_real_escape_string($value)."'");
$result = mysql_query($sql);
The main point is that you need to pass in the string NULL (without quotes) if the value should be null and the string 'val' if the value should be "val". Note that since we are writing string literals in PHP, in both cases there is one more pair of quotes in the source code (this makes one pair in the first case, two pairs in the second).
Warning: When inserting to the database directly from request variables, it is very easy to be wide open to SQL injection attacks. Do not be another victim; read about how to protect yourself and implement one of the universally accepted solutions.
For what I understand when something is not filled the post variable is not set as an empty value but rather not set at all so in php you'd do for example:
$genre = isset($_POST['genre']) ? $_POST['genre'] : NULL;
Here's how I do it. I don't like sending anything to an SQL query right from POST (always sanitize!) in the following cas you just run through the POST vars one by one and assign them to a secondary array while checking for 0 length strings and setting them to NULL.
foreach ($_POST as $key => $value) {
strlen($value)=0 ? $vars[$key] = NULL : $vars[$key] = $value
}
Then you can build your SQL query from the newly created $vars[] array.
As Jon states above, this would be the place to also escape strings, strip code and basically do all your server side validation prior to data being inserted into the db.

Database insert in PHP returns string not defined and notice about unknown column

I'm trying to insert into a database a field called Id_Obj and it's a VarChar but when I try to send it I get an error:
Unknown Column 'Id_Obj4' in 'field List'
The insert looks like this:
while($info=mysql_fetch_Array($data))
{
print "name :".$info['Id']." ";
$count=$info['Id'];
}
$t = "INSERT INTO Table_Faces(Id_Obj,Num_Sides)VALUES(";
$t = $t."IdObj$count".",".$_GET["ns"];
$t = $t.")";
mysql_query($t);
The fields in the database are Id, Id_Obj, Num_Sides.
Couple of things:
You really want to make sure that
your values are escaped
You're missing out on your last ")"
in the query
Your strings need to be wrapped in
quotes, otherwise it thinks you're
using a table name
Your SQL can be like:
$t ="INSERT INTO Table_Faces(Id_Obj,Num_Sides)VALUES('IdObj4','". $_GET["ns"]. "')";
Also, just as a side so you know the shortcut:
$t = $t . " something added"; is the same as $t .= " something added"
You need to wrap strings with single quotes in SQL.
$ns = intval($_GET('ns')); // This should sanitize $ns enough for the db.
if ($ns > 0)
{
$t="INSERT INTO Table_Faces(Id_Obj,Num_Sides)VALUES(";
$t = $t."'IdObj4'".",".$ns . ")";
mysql_query($t);
}
You also forgot the closing parenthesis.
I have modified your code to be more resistant to SQL Injection in a very simple way. If you intend to make the Id_Obj a variable as well, you should consider using mysql_real_escape_string() to escape the value for use in your SQL statement.
When you are in a situation where your insert query is so small like this, why you don't use everything in a single line? It saves you from a lot of small problems.. I think #Mark solved your problem.

passing a null value to mysql database

A user fills out a form and if they choose to not fill out a field that is not required php does this:
if($_SESSION['numofchildren']=="")
$_SESSION['numofchildren']=null;
But when I use the session variable in a mysql query, the result is not null, but is 0. The column is a tinyint(4) that allows NULL.
Why am I getting a 0 instead of NULL?
Probably because PHP doesn't convert 'null' into 'NULL'. You are probably just inserting an empty value.
INSERT INTO TABLE (`Field`) ('')
You probably have the default for the column set to '0', and that means that it will insert a 0 unless you specify a number or NULL
INSERT INTO TABLE ('Field') (NULL)
To fix this, check for Null Values before you do the query.
foreach($values as $key => $value)
{
if($value == null)
{
$values[$key] = "NULL";
}
}
I have a feeling that prepared statements will have the foresight to do this automagically. But, if you are doing inline statements, you need to add a few more things.
MySQL values must have quotes around them, but Nulls don't. Therefore, you are going to need to quote everything else using this
foreach($values as $key => $value)
{
if($value == null)
{
$values[$key] = "NULL";
}
else
{
// Real Escape for Good Measure
$values[$key] = "'" . mysql_real_escape_string($value) . "'";
}
}
Then, when you create the statement, make sure to not put quotes around any values
$SQL = "INSERT INTO TABLE (Field) VALUES(".$values['field'].")";
turns into
$SQL = "INSERT INTO TABLE (Field) VALUES("Test Value")";
or
$SQL = "INSERT INTO TABLE (Field) VALUES(NULL)";
Have a look at the table definition for whichever table you're inserting into. The 'default' value for that field is probably set to zero.
The version of MySql you are using is quite important in determining precisely how MySql treats Data Type Default Values.
The above link says:
For numeric types, the default is 0,
with the exception that for integer or
floating-point types declared with the
AUTO_INCREMENT attribute, the default
is the next value in the sequence.
You all where probably right, but all I had to do is put quotes around the null.
if($_SESSION['numofchildren']=="")
$_SESSION['numofchildren']='NULL';
I had the same problem some minutes ago, but then I figured it out. In my case I was making the query with the NULL variables between quotes like these ", '. Let me explain myself...
This is what you want to do:
INSERT INTO `tbl_name` (`col1`, `col2`) VALUES (NULL,"some_value");
So if you want to use a NULL variable it should be "NULL", like this:
$var1="NULL"; $var2="some_value";
Now, if you want to use $var2, you will type '$var2' in the query, but you shouldn't do the same for $var1:
INSERT INTO `tbl_name` (`col1`, `col2`) VALUES ($var1,'$var2');
If you put $var1 between quotes, you'll get a 0 instead NULL.
For me it didn't work to put NULL var in database, I used var char(2).
So I just made 2 queries. This way it will work 100%. For your example it would be:
if($_SESSION['numofchildren']=="")
{
$updatequery="
UPDATE table
SET table1='$value', table2='$value2', numofchilrdrentable=(NULL)
";
}
else
{
$updatequery="
UPDATE table
SET table1='$value', table2='$value2', numofchilrdrentable='$_SESSION[numofchildren]'
";
}
$updatequeryresult=mysql_query($updatequery) or die("query fout " . mysql_error() );
edit: var char -> var char(2)
null parsed to string becomes 0. Try using is_null() to check that first and place NULL instead of 0 in the query.
Or, try using PDO and PDO::prepare for a perfect and hacker-safe query.
It's very confusing especially when values were posted from a web form. I do it like that:
We assume you need a database field named 'numofchildren' that will accept possible values: NULL, 0, 1, 2.., etc. up to 99 and default should be the SQL NULL value.
SQL field should be defined as:
.. `numofchildren` INT( 2 ) NULL DEFAULT NULL
When you insert your data for the NULL values you pass strings like 'NULL' and look for them when looping the incoming data. The other values you just cast to integers:
foreach ($data as $v) {
$v['numofchildren'] = !isset($v['numofchildren']) || $v['numofchildren'] === 'NULL' ? '(NULL)' : (int) $v['numofchildren'];
$q = "INSERT INTO tablename (numofchildren) VALUES ({$v['numofchildren']}) ";
...
}
Note that {$v['numofchildren']} in SQL query is not surrounded with single quotes because you do not pass strings but integers (0,1,2..) or SQL NULL.
I believe it's clear and short and covers the issue.
if you want set NULL for any column in DATABASE
at first
You should check is_null for that column
secuond :if the variable you want
Set to null code you must insert "null" in double quote then submit to database
If you set null to double quote("") nothing, nothing will be sent and the database will get an error
for example :
function insert_to_db($var){
...
sql="INSERT INTO table VALUES($var)"
...
}
when you use in code with "" and without "" =>
function insert_to_db(null)// error : INSERT INTO table VALUES()
correct:
function insert_to_db("null")//its ok

Categories