sprintf在mysql中插入null

p8h8hvxi  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(240)

早上好,我拼命想解决一个问题,在MySQL5.7.19中插入空白的日期值,3天后就来这里寻求帮助。
db被设置为允许空值-默认空值,前端字段有时被填充,通常不是空值。
出现错误:
无法执行sql语句:第1行“signedupdate”列的日期值“”不正确
插入

$lastInsertId = $this->GetConnection()->GetLastInsertId();
$sql = sprintf("INSERT INTO tbl_lead (client_id, signedupdate, plan_type) VALUES(%d, '%s', '%s');", $lastInsertId, $rowData['signedupdate'], $rowData['plan_type']);
$this->GetConnection()->ExecSQL($sql);

更新

$sql = sprintf("UPDATE tbl_lead SET signedupdate = '%s', plan_type = '%s'WHERE client_id = %d;", $rowData['signedupdate'], $rowData['plan_type']);
$this->GetConnection()->ExecSQL($sql);

有人能看出我哪里出错了吗?

am46iovg

am46iovg1#

尝试在执行查询字符串之前回显该字符串,并在phymyadmin中复制/粘贴回显的查询,并检查查询中是否存在错误

$lastInsertId = $this->GetConnection()->GetLastInsertId();
$sql = sprintf("INSERT INTO tbl_lead (client_id, signedupdate, plan_type) VALUES(%d, '%s', '%s');", $lastInsertId, $rowData['signedupdate'], $rowData['plan_type']);
echo $sql;

$this->GetConnection()->ExecSQL($sql);
9udxz4iz

9udxz4iz2#

在sql(如php)中 NULL 值和一个恰好有字母n-u-l-l的正则文本变量。只要源变量是实际变量,任何像样的数据库库都会自动处理这个问题 null (而不是文本) 'null ')并按预期使用库。
您使用的是自定义数据库库,因此很难说是哪种情况。如果库不是太差,它应该提供如下语法:

$sql = 'INSERT INTO tbl_lead (client_id, signedupdate, plan_type) VALUES (?, ?, ?)';
$this->GetConnection()->ExecSQL($sql, [
    $lastInsertId,
    $rowData['signedupdate'],
    $rowData['plan_type']
]);

当然,不一定是这种语法。请参考图书馆文档,检查其源代码。
如果它是一个坏库,它只提供转义函数。如果这些函数自动添加引号,您可能会幸运地发现:

$sql = sprintf('INSERT INTO tbl_lead (client_id, signedupdate, plan_type) VALUES(%s, %s, %s)',
    $this->GetConnection()->EscapeValue($lastInsertId),
    $this->GetConnection()->EscapeValue($rowData['signedupdate']),
    $this->GetConnection()->EscapeValue($rowData['plan_type'])
);
$this->GetConnection()->ExecSQL($sql);

再说一遍,我只是编了语法。
否则,你将不得不自己处理一切:

$sql = sprintf('INSERT INTO tbl_lead (client_id, signedupdate, plan_type) VALUES(%s, %s, %s)',
    $lastInsertId===null ? 'NULL' : "'" . $this->GetConnection()->EscapeValue($lastInsertId) . "'",
    $rowData['signedupdate']===null ? 'NULL' : "'" . $this->GetConnection()->EscapeValue($rowData['signedupdate']) . "'",
    rowData['plan_type']===null ? 'NULL' : "'" . $this->GetConnection()->EscapeValue($rowData['plan_type']) . "'"
);
$this->GetConnection()->ExecSQL($sql);

如果库甚至不提供转义函数,你真的应该停在这里,切换到例如pdo。在我的经验中,切换甚至可能是个好主意,奇怪的是CasedLibraries()的质量往往令人怀疑。

相关问题