[英]PHP How to insert NULL in Database?
I have a normal HTML-File that give a string via. 我有一个普通的HTML文件,可以通过它提供字符串。 POST to my PHP-file wich will put this to a MySQL-database.
POST至我的PHP文件,将其放入MySQL数据库。
How do I achieve that I can write a "real" NULL
in the database and not " " (a empty string) or something like that? 如何实现可以在数据库中写入“真实”
NULL
而不是“”(空字符串)之类的东西?
The MySQL column is nullable. MySQL栏可为空。
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文件:
<?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:
并且由于您很容易受到sql注入攻击,因此应将其视为强制性的:
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()
内添加引号。 If there's some text to be done, the sql-escaped text is surrounded by quotes. 如果要完成一些文本,则用sql转义的文本会用引号引起来。 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
。这归结为null
和'null'
之间的区别。
null
is an sql null, "unknown value". null
是sql null,即“未知值”。 'null'
is a string with the literal characters n
, u
, l
, and l
in it. 'null'
是一个字符串,其中包含文字字符n
, u
, l
和l
。 In SQL terms, they're two completely different things. 用SQL术语来说,它们是完全不同的两件事。
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. 现在,在插入数据库时,使用$ 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. 编辑:如果将来要切换到PDO,则需要使用prepare语句,或者转义用户输入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.