Null X Zero issue - php

Ok, this is driving me crazy!!
Got a MySQL table with an integer field default set to null.
Need to update it through a form submission. If form field is blank, set database field to NULL, ELSE set database field to form submission value.
So, in PHP I have: (staging code, still needs to be sanitized)
if($_POST['vendor-product'] != ''){
$ms2VendorID = $_POST['vendor-product'];
}else{
$ms2VendorID = '';
}
The problem is that instead of NULL it enters a zero. I've tried several different ways and nothing seems to be working.
Thanks for any help.

Why don't you assign NULL (as a string) to your variable in the else statement?
if($_POST['vendor-product'] != ''){
$ms2VendorID = $_POST['vendor-product'];
}else{
$ms2VendorID = "NULL";
}
Also, make sure that the field has not the NOT NULL constraint enabled.

Related

How to update a date value that is blank on MSSQL?

I am creating a form that extracts user info, and the users can update their info if needs be. On the form there are two date fields, the second field is optional. So when the user clicks UPDATE and the second date field is blank, in MSSQL database it updates the date_two field with "01/01/1970". I am using PHP with MSSQL, so in the code I have:
if(isset($_POST['update']) {
$date_two = $_POST['date_two'];
if($date_two == "")
$date_two == NULL;
else
$date_two = date("Y-m-d", strtotime($date_two) );
UPDATE table SET date_two = CAST('$date_two' as DATE2);
}
The resulted entry is 01/01/1970, instead of NULL.
you should check if your input date value is a emprty string ('') and manage for null because if the value of your var is not null (also an empty string)
the update produce a date value
UPDATE table SET date_two = (case when '$date_two' = '' then NULL
else CAST('$date_two' as DATE2)
end);
anyway you should not use php var in your sql command you are at rusk for sqlinjection .. take a lool at you db driver fior prepared command and binding param ..

SQL update to NULL using a variable

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

insert null value in date column in access when date is empty

I am in problem is that, i am using php ms access databse, when i am trying to update date in database its not updating, i want to update date field when user put date and when date is null column value should be null, my code following
if($cDate==NULL){
$cDate='Null';
}
else {
$cDate='02/03/2016';
}
if($buttonName=="Update"){
$sql_update="UPDATE 0D1_INDEX set C_date=$cDate where DN_='$mdn'";
and when date inserted it become time
Try This,
Set Default Value to NULL in Database
If I understand your question correctly you could use the isset() function to determine if the value of $cDate is null.
So you would have to do something like so:
if(!isset($cDate)){
$cDate = "Null";
} else{
$cDate='02/03/2016';
}
isset() determines if the value is not NULL so putting an ! in front of it means that if the value is NULL

Why is my php "if statement" not affecting my mysql query?

First of all, I know mysql is deprecated. Will change to mysqli as soon as I figure out the issue at hand. My query continues to update all my rows even if the data is not set in the 'stripetoken' column. Why is this happening?
Code snippet:
$token_query = 'SELECT * FROM jobsubmission';
$token_res = mysql_query($token_query);
$token_row = mysql_fetch_array($token_res);
if(isset($token_row['stripetoken'])) {
$updqry = 'UPDATE jobsubmission SET assigned=1 WHERE ID="'.$book_ids[$jcount].'"';
$update = mysql_query($updqry);
$bookdate = date("d-m-Y");
Because $token_row['stripetoken'] is always set because it is a column in your database and it will be available in $token_row as a result. Now whether it has a value or not is a different story. You should be using empty() instead (assuming you don't want it to be true for falsy values).
if(!empty($token_row['stripetoken'])) {
So while #JohnConde was absolutely correct in saying I needed to use the empty function over the isset, my solution layed elsewhere. Here is how I managed to get the query to work to my specifications:
instead of searching for empty, I made the 'stripetoken' column NULL
by default.
This allowed me to use the following code:
$token_query = 'SELECT * FROM jobsubmission WHERE ID="'.$book_ids
[$jcount].'" and stripetoken is not null';
$token_res = mysql_query($token_query);
$token_row = mysql_fetch_object($token_res);
if(!$token_row->stripetoken == NULL) {

MySQL: In PHP, a DELETE statement will replace some values with NULL instead of deleting

I have a table in my database I'm trying to delete a row from.
When I use the query DELETE FROM Exercises WHERE id = 2 in PHP, it simply ends up setting the exercise_name variable to NULL, and the submission_deadline variable to '0000-00-00 00:00:00', leaving every other field fully intact (probably because the other fields are explicitly defined as "NOT NULL".
The weirdest thing, is that when I literally use the same, copied and pasted query in console, the row gets properly removed. In both cases, I'm logged in as root in MySQL, so permissions shouldn't be a problem.
Here's the table in my database I'm trying to delete a row from:
DROP TABLE IF EXISTS `Exercises`;
CREATE TABLE `Exercises` (
`id` INTEGER NULL AUTO_INCREMENT DEFAULT NULL COMMENT 'Unique ID of this exercise',
`exercise_name` MEDIUMTEXT NULL DEFAULT NULL COMMENT 'Descriptive name of this exercise',
`default_state_data` MEDIUMTEXT NOT NULL COMMENT 'The default state data for this exercise',
`solution_data` MEDIUMTEXT NOT NULL COMMENT 'Example solution for this exercise.',
`solution_gate` MEDIUMTEXT NOT NULL COMMENT 'The label of the gate that will be compared',
`submission_deadline` DATETIME NOT NULL DEFAULT '9999-12-31 23:59:59' COMMENT 'Deadline for the submission of answers to this exercise',
PRIMARY KEY (`id`)
) COMMENT 'All logic gate exercises';
NOTE: In case that matters, the above "id" is referenced as a foreign key in two other places.
For testing purposes, I populate it with two rows, as follows:
INSERT INTO `Exercises` (`exercise_name`,`submission_deadline`, `default_state_data`, `solution_gate`, `solution_data`) VALUES
('Logic Gate Playground','2016-03-30 23:59:59', '<massive json object>', 'S_OR', '<massive json object>');
INSERT INTO `Exercises` (`exercise_name`,`submission_deadline`, `default_state_data`, `solution_gate`, `solution_data`) VALUES
('Building with NAND','2016-04-07 23:59:59', '<massive json object>', 'XNOR', '<massive json object>');
An excerpt of the PHP code I'm using to delete a row from this table:
$exercise_id = intval($_POST['exercise_id']);
// Let's remove the exercise with a prepared statement
$prepared_statement = $mysql_connection->prepare("DELETE FROM Exercises WHERE id = ?");
$prepared_statement->bind_param("i", $exercise_id);
$result = $prepared_statement->execute();
Also, after that failed, I tried a simpler version of the above to test if that would work (it didn't):
$exercise_id = intval($_POST['exercise_id']);
// Let's remove the exercise
$result = mysqli_query($mysql_connection, "DELETE FROM Exercises WHERE id = {$exercise_id}");
I also tried adding single quotation marks around the variable I'm inputting.
At this point, I'm at a complete loss. Does anyone have any insight into why this would possibly be happening?
EDIT:
When I replaced the entire PHP file with the following, it worked and deleted the entire row properly):
<?php
require_once '../includes/database-connect.php';
mysqli_query($mysql_connection, "DELETE FROM Exercises WHERE id = 2");
That still leaves me wondering why my original file doesn't work. Here's the entire file (that doesn't work):
<?php
require_once '../includes/database-connect.php';
require_once '../includes/functions.php';
$_SESSION['user_id'] = 'adm12345'; // TODO Remove debug line
// Check if the mysql connection is established
if (!$mysql_connection) {
echo "<b>Failed to connect to MySQL database; MySQL error below:</b><br><pre><code>".mysqli_error($mysql_connection)."</code></pre>";
}
// Retrieve the user ID from the session
$user_id = check_login($mysql_connection, TRUE);
if ($user_id) {
// User is logged in as an admin
$exercise_id = intval($_POST['exercise_id']);
// Let's remove the exercise with a prepared statement
$prepared_statement = $mysql_connection->prepare("DELETE FROM Exercises WHERE id = ?");
$prepared_statement->bind_param("i", $exercise_id);
$result = $prepared_statement->execute();
if ($result) {
echo 1;
} else {
$error = mysqli_error($mysql_connection);
if ($error) {
echo "<b>Failed to submit to server; MySQL error below:</b><br><pre>" . mysqli_error($mysql_connection) . "</pre>";
} else {
echo "<b>Failed to submit to server even though MySQL did not throw an error.</b>";
}
}
} else {
if (isset($_SESSION['user_id'])) {
echo "<b>You are not an admin, you cannot delete exercises.</b>";
} else {
echo "<b>You're not logged in.</b>";
}
}
The DELETE statement, if successful deletes data. If unsuccessful it does not change the data. It does not update values to null. If you are seeing null values after issuing a DELETE statement, the fault is in the code you are reading those values back with.

Categories