私はデータベース更新クエリが成功していることを確認する正しい方法を見つけようとしていましたが、フェッチしているいくつかの問題があります。 update query($db->execute()
)が行われなかったり、行が存在しない場合でも...それはtrueを返し、成功したことを意味しますが、これは誤りです。 $db->getaffectedrows()
メソッドの結果は不完全です(oと1のみ)。 joomlaコードのデバッグ中に、データベースオブジェクト($db = jfactory:getdbo()
)の接続オブジェクトにinfoプロパティがあるという方法を見つけました。このプロパティは、更新クエリによって一致した行(テーブルで見つかったデータ行)があるかどうかを示します行が変更されたか(新しい値で更新されたか)。行が見つかった、行が見つかったが列の値が変更されていない、行が見つかり、列の値が変更されたすべての条件を考慮して、更新が実際に成功したかどうかを確認するためのより良い方法/クエリはありますか?... joomla cmsフレームワークの下で?
以下は、各結果を分離するための基本的な構造です。
_$id = 2286; // you can jinput this or whatever
$found = 0; // establish default value
$affrows = 0; // establish default value
$db = JFactory::getDBO();
try {
$select_query = $db->getQuery(true)
->select("COUNT(*)")
->from("#__users")
->where("id = " . (int)$id);
$db->setQuery($select_query);
if ($found = $db->loadResult()) { // if a positive count
$update_query = $db->getQuery(true)
->update("#__users")
->set("block = 1")
->where("id = " . (int)$id);
$db->setQuery($update_query);
$db->execute();
if ($affrows = $db->getAffectedRows()) { // if a positive count
JFactory::getApplication()->enqueueMessage("Update Successful: Found: $found; Updated: $affrows");
} else {
JFactory::getApplication()->enqueueMessage("Fruitless Update (No Changes): Found: $found; Updated: $affrows", "notice");
}
} else {
JFactory::getApplication()->enqueueMessage("Update Ignored - No Qualifying Rows: Found: $found; Updated: $affrows", "notice");
}
} catch (Exception $e) {
JFactory::getApplication()->enqueueMessage('Query Syntax Error (Select or Update Failed): Found: $found; Updated: $affrow', 'error');
// $query->dump() . "<br>" . $e->getMessage() // <-- not to be displayed publicly
}
_
上記では$db->qn()
または$db->q()
呼び出しを使用していません。これは、テーブル名と列が単一の単語であり、「予約済み」のmysqlキーワードワードではなく、_$id
_値が整数であるためです。セキュリティ上の理由から、_(int)
_でハードキャストします。
これは、 行が存在しないときにINSERTを実行する を行い、それらの結果を確認したくないことを前提としています。