gpt4 book ai didi

PHP如何在数据库中插入NULL?

转载 作者:行者123 更新时间:2023-11-29 07:43:53 24 4
gpt4 key购买 nike

我有一个普通的 HTML 文件,它给出了一个字符串 via。 POST 到我的 PHP 文件,这会将其放入 MySQL 数据库。

如何才能在数据库中写入“真实”NULL,而不是“”(空字符串)或类似的内容?

MySQL 列可为空。

我的表格:

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

我的 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!";

?>

最佳答案

您需要预处理文本。因为你很容易受到sql injection attacks的影响这应该被视为强制性的:

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

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

注意如何在 if() 中添加引号。如果需要完成一些文本,则 sql 转义文本会用引号引起来。如果根本没有文本,则会添加字符串 null。这可以归结为 null'null' 之间的区别。

null 是一个 sql null,“未知值”。 'null' 是一个包含文字字符 null< 的字符串 在其中。在 SQL 术语中,它们是两个完全不同的东西。

上面的代码会产生

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

关于PHP如何在数据库中插入NULL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28369858/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com