How can I insert a NULL with PHP/MySQL

admin

Administrator
Staff member
The following code works great except that it inserts the string 'NULL' instead of actually inserting a NULL into the "inactive" field. I tried it without the quotes around NULL, but got the same results. How can I insert an actual NULL in the field when the value of "inactive" is a string of 0 length? - Thanks, Mike Acklin

<?php

//add.php

require("globals.php") ;
require("common.php") ;

//protect from the "'" character
$store=implode("'",(explode("'",$store)));
$address=implode("'",(explode("'",$address)));
$city=implode("'",(explode("'",$city)));

$addStmt = "Insert into $tableName(store_id, store, address, address2, city, state, zip, country, region, phone, fax, url, email, occ, occ_fl, vis, jim, alv, laz_b, laz_bm, inactive) values('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')" ;

// Check if all the variables are entered
if (!$store_id || !$store || !$address || !$city || !$state || !$zip || !$country || !$region || !$phone ) {
DisplayErrMsg(" Error: All fields with an * are mandatory") ;
exit() ;
}

// Insert Null is inactive field is left blank
IF (strlen($inactive)==0) {
$inactive = "NULL";
}
ELSE {
$inactive = "'$inactive'";
}

// Connect to the Database
if (!($link=mysql_pconnect($hostName, $userName, $password))) {
DisplayErrMsg(sprintf("error connecting to host %s, by user %s",
$hostName, $userName)) ;
exit() ;
}

// Select the Database
if (!mysql_select_db($databaseName, $link)) {
DisplayErrMsg(sprintf("Error in selecting %s database", $databaseName)) ;
DisplayErrMsg(sprintf("error:%d %s", mysql_errno($link), mysql_error($link))) ;
exit() ;
}

// Execute the Statement
if (!mysql_query(sprintf($addStmt,$store_id, $store, $address, $address2, $city, $state, $zip, $country, $region, $phone, $fax, $url, $email, $occ, $occ_fl, $vis, $jim, $alv, $laz_b, $laz_bm, $inactive), $link)) {
DisplayErrMsg(sprintf("Error in executing %s stmt", $stmt)) ;
DisplayErrMsg(sprintf("error:%d %s", mysql_errno($link), mysql_error($link))) ;
exit() ;
}

GenerateHTMLHeader("The entry was added succesfully");

ReturnToAdd();

?>
 
Back
Top