問題描述
我正在處理一個 MySQL 表,該表將 JobName 列定義為 UNIQUE.如果有人嘗試使用數據庫中已有的 JobName 將新 Job 保存到數據庫中,MySQL 會拋出警告.
I'm dealing with a MySQL table that defines the JobName column as UNIQUE. If somebody tries to save a new Job to the database using a JobName that is already in the database, MySQL throws a warning.
我希望能夠在我的 PHP 腳本中檢測到這個警告,就像一個錯誤一樣,并進行適當的處??理.理想情況下,我想知道 MySQL 拋出了什么樣的警告,以便我可以分支代碼來處理它.
I would like to be able to detect this warning, just like an error, in my PHP script and deal with it appropriately. Ideally I would like to know what kind of warning MySQL has thrown so that I can branch the code to handle it.
這可能嗎?如果沒有,是因為MySQL沒有這個能力,PHP沒有這個能力,還是兩者都有?
Is this possible? If not, is it because MySQL doesn't have this ability, PHP doesn't have this ability, or both?
推薦答案
對于本地標記"到 PHP 的警告需要更改 mysql/mysqli 驅動程序,這顯然超出了本問題的范圍.相反,您將不得不基本上檢查您對數據庫所做的每個查詢是否有警告:
For warnings to be "flagged" to PHP natively would require changes to the mysql/mysqli driver, which is obviously beyond the scope of this question. Instead you're going to have to basically check every query you make on the database for warnings:
$warningCountResult = mysql_query("SELECT @@warning_count");
if ($warningCountResult) {
$warningCount = mysql_fetch_row($warningCountResult );
if ($warningCount[0] > 0) {
//Have warnings
$warningDetailResult = mysql_query("SHOW WARNINGS");
if ($warningDetailResult ) {
while ($warning = mysql_fetch_assoc($warningDetailResult) {
//Process it
}
}
}//Else no warnings
}
顯然,使用整體應用會非常昂貴,因此您可能需要仔細考慮警告可能出現的時間和方式(這可能會導致您進行重構以消除它們).
Obviously this is going to be hideously expensive to apply en-mass, so you might need to carefully think about when and how warnings may arise (which may lead you to refactor to eliminate them).
作為參考,MySQL 顯示警告
當然,您可以省去對 SELECT @@warning_count
的初始查詢,這樣可以為您每次執行節省一個查詢,但我為了迂腐的完整性而包含它.
Of course, you could dispense with the initial query for the SELECT @@warning_count
, which would save you a query per execution, but I included it for pedantic completeness.
這篇關于我可以用 PHP 檢測和處理 MySQL 警告嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!