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
https://forums.phpfreaks.com/topic/199794-mysql_real_escape_string-problem/
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.

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)));

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.