json_decode在发布请求时返回null而不是NULL,这使我无法在数据库中设置NULL

Mic*_*elo 0 php mysql sql null

我有一个问题,我需要能够在mysql数据库中放入NULL值。因此,从前端我发送了一个基​​本的javascript对象:

{
 "Info": {
  "Name": "Michelangelo",
  "Date" : null
  }
}
Run Code Online (Sandbox Code Playgroud)

在我的PHP文件中,我确实正确获取了请求并对其进行了解码:

if(isset($postdata) && !empty($postdata)) {
  // Extract the data.
  $request = json_decode($postdata);
}
Run Code Online (Sandbox Code Playgroud)

它适用于字符串,布尔值,整数,但不适用于null值。像nullnot 解码后将在PHP中输出NULL。据我所知,PHP中唯一正确的值是NULL:https : //www.php.net/manual/en/language.types.null.php

我把这样的值放在数据库中。日期列是日期类型,它接受NULL值。但是随着null它将被转换为0000-00-00;

  $sql = "UPDATE `users` SET 
  `Username`='$request->Info->Name',
  `Date`='$request->Info->Date' //DB accepts NULL but not null (tested)
  WHERE `id` = '{$id}' LIMIT 1";
Run Code Online (Sandbox Code Playgroud)

那为什么不能正确转换呢?我知道我可以遍历对象,并null用NULL值替换所有的对象,但是由于对象具有嵌套,这将是一个很大的麻烦。我该如何解决?为什么会这样?我更愿意使用PHP而不是在sql查询中执行此操作。

Che*_*ass 5

问题是因为您将“ null”放在单引号之间!

`Date`='$request->Info->Date'
Run Code Online (Sandbox Code Playgroud)

解决方案:在准备好的语句中使用绑定参数。 https://www.php.net/manual/zh/pdo.prepare.php

$pdo = new PDO($dsn, $user, $pass, $options);
$sth = $pdo->prepare("UPDATE `users` SET
  `Username`=:username, `Date`=:date
  WHERE `id` = :id LIMIT 1");
$sth->bindParam(':username', $request->Info->Name, PDO::PARAM_STR);
$sth->bindParam(':date', $request->Info->Date);
$sth->bindParam(':id', $id);
$sth->execute();
Run Code Online (Sandbox Code Playgroud)

您应该构建一些验证类,在该类中它将从您要在查询中使用的请求中返回正确的(经过消毒的)值。

考虑创建一些类似的类/逻辑

final class InfoRequest
{
    /** @var array */
    private $info;

    public function __construct($request)
    {
        $this->info = $request->Info;
    }

    public function date(): ?string
    {
        $date = $this->info['Date'];
        if (!$this->isValidDate($date)) {
            throw NotValidDateException();
        }
        if (!$date) {
            return null;
        }
        $dateTime = new \DateTime($this->info['Date']);

        return $dateTime->format('Y-m-d');
    }

    private function isValidDate($date): bool
    {
        return true; // TODO: Not implemented yet
    }

    public function name(): string
    {
        $name = $this->info['Name'];
        if (!$this->isValidName($name)) {
            throw NotValidNameException();
        }

        return $name;
    }

    private function isValidName($name): bool
    {
        return true; // TODO: Not implemented yet
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

$info = new InfoRequest($request);
$sth->bindParam(':username', $info->name(), PDO::PARAM_STR);
Run Code Online (Sandbox Code Playgroud)

除此之外,永远不要将请求的直接输入传递给原始查询到数据库。