MySQL ERROR: Column 'Time' cannot be null
I get the error: Column 'Time' cannot be null when using the query below, it works fine the first time when there is no duplicate but then when trying to update again I get the error:开发者_运维知识库 Column 'Time' cannot be null
mysql_query("
INSERT INTO
$table(Username, Time, Videos, Credits)
VALUES
('$user', '$time', '$videos', '$credits')
ON DUPLICATE KEY UPDATE
Time=Time+INTERVAL $time SECOND
Videos=Videos+'$videos',
Credits=Credits+'$credits'
",
$conn
);
Hope you can spot my error as I am new to this, thanks!
Here is some more of my code:
$conn = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
mysql_select_db(DB_NAME, $conn);
// Error checking
if(!$conn) {
die('Could not connect ' . mysql_error());
}
// Localize the GET variables
$user = isset($_GET['username']) ? $_GET['username'] : "";
$time = isset($_GET['time']) ? $_GET['time'] : "";
$videos = isset($_GET['videos']) ? $_GET['videos'] : "";
$credits = isset($_GET['credits']) ? $_GET['credits'] : "";
// Protect against sql injections
$user = mysql_real_escape_string($user);
$time = mysql_real_escape_string($time);
$videos = mysql_real_escape_string($videos);
$credits = mysql_real_escape_string($credits);
$secret = mysql_real_escape_string($secret);
// Insert
$retval = mysql_query("
INSERT INTO
$table(Username, Time, Videos, Credits)
VALUES
('$user', '$time', '$videos', '$credits')
ON DUPLICATE KEY UPDATE
Time = DATE_ADD(IFNULL(Time,now()),INTERVAL '$time' SECOND),
Videos = Videos+'$videos',
Credits = Credits+'$credits'
",
$conn
);
// End Query
if($retval) {
echo "Success! Updated $user with Time: $time - Videos: $videos - Credits: $credits";
} else {
echo "<b>ERROR:</b><br>" . mysql_error();
}
mysql_close($conn);
It should be:
mysql_query("
INSERT INTO
$table(Username, `Time`, Videos, Credits)
VALUES
('$user', '$time', '$videos', '$credits')
ON DUPLICATE KEY UPDATE
Time = DATE_ADD(IFNULL(`Time`,now()),INTERVAL '$time' SECOND)
,Videos = Videos+'$videos'
,Credits = Credits+'$credits'
",
$conn
);
Don't forget to put single quotes around all injected variables, otherwise mysql_real_escape_string
will not protect you.
See:
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add
If there's no duplicate, then this query will do an insert, and the Time
value will be null, as no value was ever set. Null + anything
is null, hence the error.
Try ... Time = COALESCE(Time, 0) + INTERVAL $time SECOND
or similar to get aroun dit.
精彩评论