3

I've looked around and have noticed a few people have had the same problem but their oversight doesn't seem to apply here.

I have a PHP function to add an array of values into a table. It first checks whether the values are empty and if so replaces them with NULL, in order to place a null in the table field. Each fields that I'm placing null into allows for null yet places a 0 there instead.

Here's some code:

public static function AddGame($array, $tId)
{
    global $db; // Bring DB into scope
    // Get IDs from particular names
    $locId = $array['fLocation'];
    // Ensure empty values are SQL null
    $hTeamId = "'{$array['fHomeTeam']}'";
    $vTeamId = "'{$array['fVisitTeam']}'";
    $hScore = "'{$array['fHomeScore']}'";
    $vScore = "'{$array['fVisitScore']}'";
    $hHoldFor = "'{$array['fHomeHoldFor']}'";
    $vHoldFor = "'{$array['fVisitHoldFor']}'";
    // Prepare row for insertion
    $row = "'','$tId','$locId',$hTeamId,$vTeamId,'{$array['fDate']}','{$array['fTime']}',$hScore,$vScore,'{$array['fGameType']}',$hHoldFor,$vHoldFor";
    $stmt = $db->prepare("INSERT INTO `game` VALUES($row)");
    if($stmt->execute()) return true;
    else return false;
}

I've debugged this function at various lines and have dumped the $row string and it shows this, which is expected:

'','1','1','21','21','10/10/12','10:30AM','NULL','NULL','pool','NULL','NULL'

Yet when I check the table text type fields literally have the value NULL which is not what I want and also int fields show as 0. If I leave the values blank or as PHP's null then text fields show as empty (or properly null as I'd like) yet the ints still show as 0.

I expect this is only caused due to the way I insert the values indirectly.

Here is the SHOW CREATE TABLE game

CREATE TABLE `game` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `tId` int(11) NOT NULL,
  `Lid` int(11) NOT NULL,
  `hTeamId` int(11) DEFAULT NULL,
  `vTeamId` int(11) DEFAULT NULL,
  `date` text NOT NULL,
  `time` text NOT NULL,
  `hScore` int(11) DEFAULT NULL,
  `vScore` int(11) DEFAULT NULL,
  `type` text NOT NULL,
  `hHoldFor` text,
  `vHoldFor` text,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=latin1

UPDATE:

INSERT INTO `game` VALUES('','1','1','','','10/09/12','9:30AM','','','pool','winner of pool A','winner of pool B')
0

4 Answers 4

8

You are physically setting the value of the wanted NULL columns to a string of 'NULL'

NULL != 'NULL'

If you set your table structure for those columns to NULL, you can omit them from your query and they will automatically be NULL on insert.

Do this instead:

if(!empty($hHoldFor)) $hHoldFor = $array['fHomeHoldFor'];

Update

I was looking further into your example and there is a second point of failure.

$row = ... ",'$hHoldFor','$vHoldFor'";

The above line, if you set $hHoldFor = NULL, will insert quotes around NULL, turning it back into a string of NULL.

Try this:

if(!empty($hHoldFor)) $hHoldFor = "'{$array['fHomeHoldFor']}'";
...  
$row = ... ",$hHoldFor,$vHoldFor";

This removes the single quotes around this value in the QUERY string and adds them to the variable itself.

Update 2

Here is an SQLFiddle using your schema. It returns NULL for NULL columns. Can you do an echo "INSERT INTOgameVALUES($row)"; and post the output? The issue is PHP is converting the NULL to 'NULL' still somewhere. This will help us get to the bottom of it.

Update 3

The issue is just as thought. Your PHP is inserting a blank string, '', into your database, which is not a NULL value. NULL is of a type, '' is a string with no length.

INSERT INTO `game` VALUES('','1','1','','','10/09/12','9:30AM','','','pool','winner of pool A','winner of pool B')

Try this:

public static function AddGame($array, $tId)
{
    global $db; // Bring DB into scope
    // Get IDs from particular names
    $locId = $array['fLocation'];
    // Ensure empty values are SQL null
    $hTeamId = (strlen($array['fHomeTeam']) != 0 ? "'{$array['fHomeTeam']}'" : 'NULL');
    $vTeamId = (strlen($array['fVisitTeam']) != 0 ? "'{$array['fVisitTeam']}'" : 'NULL');
    $hScore = (strlen($array['fHomeScore']) != 0 ? "'{$array['fHomeScore']}'" : 'NULL');
    $vScore = (strlen($array['fVisitScore']) != 0 ? "'{$array['fVisitScore']}'" : 'NULL');
    $hHoldFor = (strlen($array['fHomeHoldFor']) != 0 ? "'{$array['fHomeHoldFor']}'" : 'NULL');
    $vHoldFor = (strlen($array['fVisitHoldFor']) != 0 ? "'{$array['fVisitHoldFor']}'" : 'NULL');
    // Prepare row for insertion
    $row = "'','$tId','$locId',$hTeamId,$vTeamId,{$array['fDate']}','{$array['fTime']}',$hScore,$vScore,'{$array['fGameType']}',$hHoldFor,$vHoldFor";
    $stmt = $db->prepare("INSERT INTO `game` VALUES($row)");
    if($stmt->execute()) return true;
    else return false;
}
Sign up to request clarification or add additional context in comments.

14 Comments

I expected this was the case so I tried it without the quotes too, so = null. Which would be PHP's representation of null. This didn't work either. I'm trying your answer now though, thanks.
Ok so I defined all the variables as null first to avoid the undefined variables errors. The int fields still show as zero.
There is a second point of failure which i pointed out in update. Take a look.
That's a great point thanks. If this works, I need not the conditional for checking empty right? As regardless it'll put the value or the null in?
ok I did as you said but omitted the empty check is it doesn't seem necessary. I revised the code in the original post but those bloody ints still show as zero.
|
5

You can't insert 'NULL'. Remove the single quotes around NULL.

Your string

'','1','1','21','21','10/10/12','10:30AM','NULL','NULL','pool','NULL','NULL'

Should look like

'','1','1','21','21','10/10/12','10:30AM',NULL,NULL,'pool',NULL,NULL

You should also define a column list whenever making an INSERT (ie. INSERT INTO table (col1, col2) VALUES ...)

Edit 1

I would recommend looking through your SHOW CREATE TABLE tbl_name

Edit 2

After testing this, I would still say the problem is with how you're inserting the data.

(18,1,1,21,21,'10/10/12','10:30AM',NULL,NULL,'pool',NULL,NULL)

Works.

('18','1','1','21','21','10/10/12','10:30AM','NULL','NULL','pool','NULL','NULL')

Does not work: Incorrect integer value: 'NULL' for column 'hScore' at row 1:

Edit 3

Here is an improved version of your class:

public static function AddGame($array, $tId)
{
    global $db; // Bring DB into scope

    // Get IDs from particular names
    $locId = $array['fLocation'];

    // Ensure empty values are SQL null
    $hTeamId = empty($array['fHomeTeam']) ? 'NULL' : "'" . $array['fHomeTeam'] . "'";
    $vTeamId = empty($array['fVisitTeam']) ? 'NULL' : "'" . $array['fVisitTeam'] . "'";
    $hScore = empty($array['fHomeScore']) ? 'NULL' : "'" . $array['fHomeScore'] . "'";
    $vScore = empty($array['fVisitScore']) ? 'NULL' : "'" . $array['fVisitScore'] . "'";
    $hHoldFor = empty($array['fHomeHoldFor']) ? 'NULL' : "'" . $array['fHomeHoldFor'] . "'";
    $vHoldFor = empty($array['fVisitHoldFor']) ? 'NULL'  : "'" . $array['fVisitHoldFor'] . "'";

    // Prepare row for insertion
    $row = "$tId,$locId,$hTeamId,$vTeamId,'{$array['fDate']}','{$array['fTime']}',$hScore,$vScore,'{$array['fGameType']}',$hHoldFor,$vHoldFor";
    $stmt = $db->prepare("INSERT INTO game (tId, Lid, hTeamId, vTeamId, date, time, hScore, vScore, type, hHoldFor, vHoldFor) VALUES($row)");
    if($stmt->execute()) return true;
    else return false;
}

Non-NULL values will be encased in quotes, otherwise they are assigned NULL. I've also defined the column list for INSERT and excluded id, as it's an AUTO_INCREMENT column.

10 Comments

That still doesn't work. I mentioned I tried this at the bottom of the post.
Can you try the edited version of your string? If this doesn't work, can you reply back with what error you are receiving?
There's no error, everything inserts which is why I never bothered with defining the column names first as it just adds unneccessary complexity. The problem is the int fields showing zero instead of blank, or (null).
@Lee can you post what your SHOW CREATE TABLE tbl_name looks like?
I posted it. The navicat design view has been lying to me? :S
|
1

Does you column allows NULL values? Check the DDL again maybe you have set the DEFAULT VALUE to zero.

When you try to insert null value in a column, don not wrap it with single quote. Example

INSERT INTO tableName (colName, ColNameB) VALUES (1, NULL)

2 Comments

Yes the check boxes are ticked for allow null and they are also set to default null.
when you insert the value, do not wrap it with single quote.
0

In my case i had to display three situations: Case-empty, Case-yes and Case-no. I planned to use null, one and zero. But the null was being saved always as 0. The column i was working accepted null entries but all my nulls was being saved as zeros. My solution, was considering Case-empty as zero, Case-yes as the number one and case-no as the number two. It is a workaround but solved the problem.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.