簡體   English   中英

PHP PDO獲取null

[英]PHP PDO fetch null

如何檢查列值是否為空? 示例代碼:

$db = DBCxn::getCxn();

$sql = "SELECT exercise_id, author_id, submission, result, submission_time, total_rating_votes, total_rating_values
FROM submissions 
LEFT OUTER JOIN submission_ratings ON submissions.exercise_id=submission_ratings.exercise_id
WHERE id=:id";

$st = $db->prepare($sql);

$st->bindParam(":id", $this->id, PDO::PARAM_INT);

$st->execute();
$row = $st->fetch();

$this->total_rating_votes = $row['total_rating_votes'];

if($this->total_rating_votes == null) // this doesn't seem to work even though there is no record in submission_ratings????
{
...
}

連接到數據庫時,可以設置一些屬性來控制PDO在數據庫查詢返回時如何處理Null和Empty Strings

PDO :: setAttribute(PDO :: ATTR_ORACLE_NULLS,$ option)

其中$ option是以下之一:

  • PDO :: NULL_NATURAL:無轉換。
  • PDO :: NULL_EMPTY_STRING:空字符串轉換為NULL。
  • PDO :: NULL_TO_STRING:NULL轉換為空字符串。

不是你想做的事嗎?

foreach($row as $r){

if($r->total_rating_votes == null){

  //do something

}

其實你可能想嘗試:

if($r->total_rating_votes == ""){/*do something*/}

因為php可能已經將null值轉換為空字符串,然后它實際上不是null,所以它是“”

希望這可以幫助!

謝謝你的所有答案。 經過一些實驗,這段代碼解決了我的問題

$this->total_rating_votes = $row['total_rating_votes'];

if(!isset($this->total_rating_votes)) // this is now true if this record had a NULL value in the DB!!!
{
...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM