[英]Sprintf inserting NULL into mysql
早上好,拼命嘗試解決將空白日期值插入MySQL 5.7.19的問題,並在3天后轉向此處尋求幫助。
DB設置為允許NULL-默認NULL,有時會填充前端字段,但通常不填充null值。
錯誤彈出:
無法執行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);
誰能看到我可能要出問題的地方?
嘗試在執行之前回顯查詢字符串,然后在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);
在SQL中(與PHP中一樣), NULL
值和恰好具有字母NULL的常規文本變量之間存在很大差異。 只要源變量是實際的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。 無論如何,切換甚至是一個好主意-根據我的經驗,StrangelyCasedLibraries()的質量往往令人懷疑。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.