[英]Need some advice on error handling in PHP / mysql
我不確定向終端用戶提供READABLE反饋時最適合使用哪種方法。 我已經閱讀了一些論壇,但並沒有真正明智(或者我不了解)
我想在插入/更新失敗,成功或自定義反饋(例如檢查是否已存在項目)時提供反饋。
在INSERT,UPDATE,DELETE,DROP等上,查詢返回TRUE或FALSE。 因此,我的結果屬性$ this-> query_result應該始終為true或false。
我的問題:
我添加了代碼以查看我在做什么(做錯了)
這些是我用於連接/查詢數據庫的功能:
public function connect()
{
if (!($this->conn = mysql_connect($this->host, $this->username, $this->pwd))) {
die("Error connecting to DB by user = " . $this->username);
}
$this->db = mysql_select_db($this->dbname,$this->conn)
or die("Unable to connect to database " . $this->dbname);
}
private function query($sql)
{
$this->query_result = mysql_query($sql, $this->conn)or die("Unable to query local database <b>". mysql_error()."</b><br>$sql");
if (!$this->query_result){
die("database query failed.");
} else {
return $this->query_result;
}
}
這是我的問題:我正在提供有關數據訪問層(DAL)的反饋,例如:
public function addNewPerson($formData)
{
$sql = "INSERT INTO my_table(`name`, `email`, `www`)";
$sql .= " VALUES('".
$formData['name']."','".
$formData['email']."','".
$formData['www']."','");
$this->query($sql);
return $this->query_result;
}
通過返回文本字符串,返回結果將始終為true。 從我的閱讀中,我可能應該有一個處理錯誤/反饋的功能。
這是我目前正在使用模板中的反饋進行的操作:
if (isset($_POST['form_submit']))
{
if (isset($_POST['person_submit'])) {
$formData = $sl->getFormData();
$result = $myDB->addNewPerson($formData);
if ($result == true)
{
echo '<script type="text/javascript" language="JavaScript">
jQuery("#contentArea .messageWindow1").show(500);
jQuery("#contentArea :input").click(function(){ jQuery("#contentArea .messageWindow1").hide(500); });
</script>';
} else {
echo '<script type="text/javascript" language="JavaScript">
jQuery("#contentArea .messageWindow2").show(500);
jQuery("#contentArea :input").click(function(){ jQuery("#contentArea .messageWindow2").hide(500); });
</script>';
}
}
}
<div id="contentArea">
<div class="messageWindow1"> <span class="msg"><?php echo $labelResult ?></span></div>
<div class="messageWindow2"> <span class="msg"><?php echo $labelResult ?></span></div>
</div>
我將使用PHP5的內置異常處理來捕獲錯誤以及可能的驗證錯誤。 例如:
class DatabaseException extends Exception {}
class ValidatorException extends Exception {}
public function connect()
{
if (!($this->conn = mysql_connect($this->host, $this->username, $this->pwd))) {
throw new DatabaseException("Error connecting to DB by user = " . $this->username);
}
if(!($this->db = mysql_select_db($this->dbname,$this->conn))) {
throw new DatabaseException("Unable to connect to database " . $this->dbname);
}
}
//....
public function addNewPerson($formData)
{
$sql = "INSERT INTO my_table(`name`, `email`, `www`)";
$sql .= " VALUES('".
$formData['name']."','".
$formData['email']."','".
$formData['www']."','");
//If less than 2 characters, do not insert data.
if (strlen($formData['name']) < 2)
throw new ValidatorException( "Person not saved. Name field was to short or empty.");
//If person already exists
if($this->isPersonInList($formData['name']))
throw new ValidatorException( "Person already exists!");
//Process query
$this->query($sql);
return $this->query_result;
}
在調用腳本中
try {
$formData = $sl->getFormData();
$result = $myDB->addNewPerson($formData);
} catch (DatabaseException $e) {
// display $e->getMessage()
} catch (ValidatorException $e) {
//display $e->getMessage()
}
您的腳本需要指出的其他幾件事。
$arr = 'Shoan'; var_dump(isset($arr[10])); //false var_dump(isset($arr[2])); //true
只是一個提示:編寫OO時應使用異常。 例如,您可以針對不同的錯誤反饋引入不同的例外。
class ValidationException extends Exception
{}
class DatabaseExceptionextends Exception
{}
throw ValidationException("Person not saved. Name field was to short or empty.");
throw DatabaseException("database query failed.");
然后,您捕獲所有這些異常,並根據異常的類型做出不同的反應。
try {
// ...
}
catch (ValidationException $e) {
// ...
}
catch (DatabaseExceptionextends $e) {
// ...
}
您可以在addNewPerson()中的錯誤消息的開頭添加一個特殊字符。 調用腳本將使用字符串函數來檢測特殊字符(這樣它就知道存在錯誤)並刪除該字符,以便在沒有該字符的情況下顯示消息。 您認為這可以滿足您的需求嗎?
必須回答我自己的示例以顯示代碼片段。 考慮Shoan的建議,我正在嘗試擴展DAL以使用PDO( 類DAL擴展了PDO )。 但這給了我黑屏。 這是我的DAL課程。
class DAL {
protected $username;
protected $pwd;
protected $host;
protected $dbname;
private $conn;
private $db;
private $query_result;
public function __construct($cfg_file = 'nf.config')
{
$config = parse_ini_file($cfg_file);
$this->username = $config['db_user'];
$this->pwd = $config['db_password'];
$this->host = $config['db_host'];
$this->dbname = $config['db_name'];
}
public function connect()
{
($this->conn = mysql_connect($this->host, $this->username, $this->pwd))
or die("Error connecting to DB by user = " . $this->username);
$this->db = mysql_select_db($this->dbname,$this->conn)
or die("Unable to connect to database " . $this->dbname);
}
private function query($sql)
{
$this->query_result = mysql_query($sql, $this->conn)
or die("Unable to query local database <b>". mysql_error()."</b><br>$sql");
if ($this->query_result){
return $this->query_result;
}
}
public function getSomeData()
{
$sql ="SELECT * FROM myTable";
//Process query
$this->query($sql);
return $this->query_result;
}
}
因此,在我的代碼中,我只是這樣做:
$ myDB =新的DAL();
$ myDB-> connect();
$ result = $ myDB-> getSomeData();
但是一旦添加了“ extends PDO ”,我的頁面就會空白。 我也無法使用任何try / catch / throw-這都給了我錯誤消息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.