简体   繁体   中英

PHP How to insert NULL in Database?

I have a normal HTML-File that give a string via. POST to my PHP-file wich will put this to a MySQL-database.

How do I achieve that I can write a "real" NULL in the database and not " " (a empty string) or something like that?

The MySQL column is nullable.

My form:

<form method="post" action="putInDatabase.php">

    <label>Text</label>
    <textarea name="text" ></textarea>

    <label>Picture URL (optional)</label>
    <input name="image" />
    <br>

    <input id="submit" name="submit" type="submit" value="submit">

</form>

My PHP-File:

<?php

  $text = "";
  $image = null;

  if (isset($_POST["submit"]))
  {
    $text = $_POST["text"];

    $image = $_POST["image"];
  }

  $text = strtr ($text, array ('"' => '\"'));


  $con = mysql_connect("censored :)");

  if (!$con)
  {
    die('ERROR' . mysql_error());
  }
  mysql_select_db("_DATABASE_HERE_", $con);


  $insertSQL = "INSERT INTO `_DATABASE_HERE_`.`_NAME_HERE_` (`Text`, `PictureURL`) VALUES ('$text', '$image ');";  

  $res = mysql_query($insertSQL); 
  $res = mysql_query($sql);

  mysql_close($con);

  echo "Success!";

?>

You'd need to pre-process your text. And since you're vulnerable to sql injection attacks this should be considered MANDATORY:

if (isset($_POST['text']) && !empty($_POST['text'])) {
   $safetext = "'" . mysql_real_escape_string($_POST['text']) . "'";
} else {
   $safetext = 'null';
}

$sql = "INSERT ... VALUES ($safetext, ...)";

Note how the quotes are added inside the if() . If there's some text to be done, the sql-escaped text is surrounded by quotes. if there's no text at all, then the string null is added in. This boils down to the difference between null and 'null' .

null is an sql null, "unknown value". 'null' is a string with the literal characters n , u , l , and l in it. In SQL terms, they're two completely different things.

The above code would produce

INSERT ... VALUES (null, ...)
INSERT ... VALUES ('Miles O\'Brien', ...)

Try this:

$variable_name = "NULL";

Now, while inserting into the database, use $variable_name.

That should do it.

EDIT: You need to either use prepare statements, if you are gonna switch to PDOs in future or escape the user input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM