MySQL insert NULL value after getting value with $_REQUEST

Mar 12, 2012   //   by   //   Blog, MySQL Tutorial  //  No Comments

I have input fields, but if the users leave it blank, i want to insert a null value to my database.

To insert a null into MySQL you have to use the SQL constant NULL

This means you have to replace ‘$val1’ with NULL in your SQL statement

Here’s the Code:


$val1 = 'NULL';
$val2 = 'NULL';
$val3 = 'NULL';

if( isset( $_REQUEST['val1'] ) && !empty( $_REQUEST['val1'] ) )
    $val1 = "'".mysql_real_escape_string( $_REQUEST['val1'] )."'";

if( isset( $_REQUEST['val2'] ) && !empty( $_REQUEST['val2'] ) )
    $val1 = "'".mysql_real_escape_string( $_REQUEST['val2'] )."'";

if( isset( $_REQUEST['val3'] ) && !empty( $_REQUEST['val3'] ) )
    $val1 = "'".mysql_real_escape_string( $_REQUEST['val3'] )."'";

mysql_query("INSERT INTO `table` ( `val1`, `val2`, `val3`) 
VALUES ($val1, $val2, $val3)");


Leave a comment

Share This Post

RSS Wordpress News