I'm assuming this should be very simple, but I can't really understand why this error happens.
I have a database like the following:
Field: id
Type: int(4) (AUTO INCREMENT)
Field: Name
Type varchar(30)
Field: Age
Type: int(3)
Everytime I leave the Age field empty on my html form, it gives me an error while trying to INSERT into the DB.
$name = $_POST['name'];
if (!isset($_POST['age'])) {
$age = 0;
} else {
$age = mysql_prep($_POST['age']);
}
INSERT INTO tage (name, age) VALUES ('$name', $age)
Printing the query, it gives me:
INSERT INTO tage (name, age) VALUES ('John',)
The error I get is the following: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '')' at line 1.
Of course this is an example database.
If I actually type 0 (the number zero) on my html form, it works fine, but if I leave it empty, the error appear and it seems I can't assign 0 to the var $age.
EDIT: It's worth to mention that I did set the field age on my database with the default value to NULL (using phpmyadmin).
Any feedback is appreciated.
Just a final EDIT so people are not under the wrong impression, this is the function mysql_prep() used on the sample code:
function mysql_prep( $value ) {
global $connection;
$magic_quotes_active = get_magic_quotes_gpc();
$new_enough_php = function_exists( "mysqli_real_escape_string" );
if( $new_enough_php ) { // PHP v4.3.0 or higher
if( $magic_quotes_active ) { $value = stripslashes( $value ); }
$value = mysqli_real_escape_string( $connection, $value );
} else { // before PHP v4.3.0
if( !$magic_quotes_active ) { $value = addslashes( $value ); }
}
return $value;
}
And the problem is now solved, and the problem was that I was under the wrong impression that empty fields weren't posted.