Jump to content

mysql_real_escape_string() problem


robert_gsfame

Recommended Posts

I just realise that single quotes '' and NULL will completely give me different result

 

and now i have another problem, how can i insert NULL value into database but still using mysql_real_escape_string() ??

 

yet if i have '' and Null , and i use if(empty())  will all records with both NULL and '' still can be retrieved

 

thanks in advance

Link to comment
Share on other sites

If you want to provide the null keyword, you can check if the data entered is blank, and define it as NULL if it is. Like so:

 

$data = empty($data) ? 'NULL', "'".mysql_real_escape_string($data)."'"; //The '' around the data are already included in this. When the data is empty it will give NULL

$query = "INSERT INTO `table` SET `field` = $data"; //We already added the single quotes in the above line.

Link to comment
Share on other sites

NULL is a keyword in mysql. Like SELECT is, or like function is in php. If you wrap it in quotes like your code did, it will just read it as the string NULL. My code that I posted will take a variable called $data and either make it into a string including the quotes for the query, or NULL, WITHOUT quotes. I can even turn it into a function

 

function nullify($data) {
   return empty($data) ? 'NULL', "'".mysql_real_escape_string($data)."'"; //The '' around the data are already included in this. When the data is empty it will give NULL
}

//Then I can use it your query:
$test = '' //Set it to an empty string if you want NULL

mysql_query(sprintf("INSERT INTO table1(column1)VALUES(%s)",
nullify($test)));

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.