1

I have an HTML form which submits values to the following PHP file, which inserts them into a MySQL database:

<?php
  $con = mysql_connect("*","*","*");
  if (!$con)
    {
    die('Could not connect: ' . mysql_error());
    }

  mysql_select_db("*", $con);

  $sql="INSERT INTO scores (hometeam, awayteam, result)
  VALUES
  ('" . mysql_real_escape_string($_POST['hometeam']) . "',
   '" . mysql_real_escape_string($_POST['awayteam']) . "',
   '" . mysql_real_escape_string($_POST['result']) . "')";

  if (!mysql_query($sql,$con))
    {
    die('Error: ' . mysql_error());
    }
  echo "1 record added";

  mysql_close($con);
?>

Sometimes an input field in the HTML form will be left empty and in this case I do not want anything inserted into the database. I want the value to remain NULL. At the moment when I fill in my form like this:

Home team: Blue team
Away team: [empty]
Result: Won

The following is inserted into my database:

Home team: Blue team
Away team: ' '
Result: Won

What I want to be inserted/not inserted is:

Home team: Blue team
Away team: NULL
Result: Won

I've hunted hours for a solution. Can anyone help? Thank you.

2
  • i guess you meant to check input for validation? Commented Jul 1, 2012 at 12:48
  • Instead of adding two quotes add the word NULL without quotes, Commented Jul 1, 2012 at 12:49

5 Answers 5

1

You can use the NULLIF function from mysql database. What it does is, it takes 2 parameters and return null if they are same. So basically you can change your code to be like following:

  $sql="INSERT INTO scores (hometeam, awayteam, result)
  VALUES
  (NULLIF('" . mysql_real_escape_string($_POST['hometeam']) . "', ''),
   NULLIF('" . mysql_real_escape_string($_POST['awayteam']) . "', ''),
   NULLIF('" . mysql_real_escape_string($_POST['result']) . "', ''))";

It will basically check if the entered value is ''(empty string), and if that's the case, it would instead save NULL in the database. You can even trim leading or trailing spaces from your variables before passing onto NULLIF, so if someone only enters spaces in your input boxes, it still saved NULL.

Also, as Michael said, it would be safer and better if you move on to PDO or mysqli extension. Hope my answer helps.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for NULLIF, sadly somewhat obscure despite being standard SQL.
1

In your code, replace:

$sql="INSERT INTO scores (hometeam, awayteam, result)
  VALUES
  ('" . mysql_real_escape_string($_POST['hometeam']) . "',
   '" . mysql_real_escape_string($_POST['awayteam']) . "',
   '" . mysql_real_escape_string($_POST['result']) . "')";

With:

if($_POST['awayteam'] == '')
 $awayteam = 'NULL';
else
 $awaytem = "'" . mysql_real_escape_string($_POST['awayteam']) "'";
$sql="INSERT INTO scores (hometeam, awayteam, result)
  VALUES
  ('" . mysql_real_escape_string($_POST['hometeam']) . "',
   " . $awayteam . ",
   '" . mysql_real_escape_string($_POST['result']) . "')";

Comments

1

Don't quote them inside your query. Instead, build variables first, and append quotes to the escaped string values outside the query, giving you the ability to insert NULL keywords if your strings are empty:

// If any is not set or empty in the POST, assign the string "NULL" unquoted to a variable
// which will be passed to MySQL as the unquoted NULL keyword.
// Otherwise escape the value from $_POST and surround the escaped value in single quotes
$ateam = !empty($_POST['awayteam']) ? "'" . mysql_real_escape_string($_POST['awayteam']) . "'" : "NULL";
$hteam = !empty($_POST['hometeam']) ? "'" . mysql_real_escape_string($_POST['hometeam']) . "'" : "NULL";
$result = !empty($_POST['result']) ? "'" . mysql_real_escape_string($_POST['result']) . "'" : "NULL";

// Then pass the three variables (already quoted if necessary) directly to the query.
$sql="INSERT INTO scores (hometeam, awayteam, result) VALUES ($hteam, $ateam, $result);

In the long run, it is recommended to begin using a MySQL API which supports prepared statements, like PDO or MySQLi. They offer better security, can handle input NULLs more elegantly, and the old mysql_*() functions are soon to be deprecated.

Comments

0

Or if you have access to db alter the columns( that are optional) and set them as NULL by default. i.e. if nothing is inserted in that column NULL will be displayed by default.

1 Comment

The current code always inserts a value in the columns (empty strings sometimes), so your idea wouldn't work.
0

Why not replace ' ' and other invalid forms of data with 'null'?

OR

Check if $_POST['data'] is equal to ' ' or '' and if true, set them to 'null'.

Also, Instead of mysql_real_escape_string, use the PHP function 'addslashes'.

3 Comments

addslashes must NOT be used to escape a string used in a mysql query! The mysql_real_escape_string exists for a reason!
Nope, mysql_real_escape_string's use is discouraged
Nahiyan, from PHP docs: To escape database parameters, DBMS specific escape function (e.g. mysqli_real_escape_string() for MySQL or pg_escape_literal(), pg_escape_string() for PostgreSQL) should be used for security reasons. DBMSes have differect escape specification for identifiers (e.g. Table name, field name) than parameters. Some DBMS such as PostgreSQL provides identifier escape function, pg_escape_indentifier(), but not all DBMS provides identifier escape API. If this is the case, refer to your database system manual for proper escaping method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.