Im working with a mysql database via php.
I have a table with some values that are = NULL
I select these values in php:
$opponentInv = db_execute("Select * from inventoryon where playerid = ".$defendid.";");
$opponentInv = mysql_fetch_assoc($opponentInv);
Then i insert the values into a another table:
db_execute("INSERT INTO `inventoryCombat` (`attackid` ,`defendid` ,`money` ,`item1` ,`item2` ,`item3`, `item4` ,`item5` ,`item6`, `time`)VALUES ('".$attackid."', '".$defendid."', '".$opponentInv["money"]."', '".$opponentInv["item1"]."', '".$opponentInv["item2"]."', '".$opponentInv["item3"]."', '".$opponentInv["item4"]."', '".$opponentInv["item5"]."', '".$opponentInv["item6"]."', '".$time."');");
The issue is that when i insert the values into the second table, they are always coming out as 0. The values in the inventoryCombat table are 0 when they should be NULL (what they are in the inventoryon table). The table is set to accept NULL as values.
Firstly I’d strongly recommend that you use prepared statements instead of building a literal SQL string. Not only is this a better practice and helps you to write a more secure application, it also handles NULL values correctly without requiring any extra work.
If you want to continue using the method you are currently using then you will need to explicitly check for undefined values and insert the string ‘NULL’ into your SQL. In other words, you need to do this:
Instead of what you are currently doing:
If it still doesn’t work, double-check that the field you are trying to insert NULL into is set to allow NULL values. You can use
SHOW CREATE TABLE inventoryCombatto do this.I’d also recommend normalizing your database. Having columns called
item1,item2,item3etc. is a sign of a bad design. Your current design will, for example, make it more complicated to perform what should be simple queries such as ‘How many players possess item X?’ or ‘Add item X to player P unless she is already holding 6 items’.