2009-06-10 283 views
0

我不确定在向最终用户提供可读反馈时最好使用哪种方法。我读过一些论坛,但没有真正得到任何明智的(或我没有明白它)在PHP/mysql中需要一些关于错误处理的建议

我想给插入/更新失败时,当它是一个成功,当给定制反馈(如检查是否一个项目已经存在)。

对于INSERT,UPDATE,DELETE,DROP等,查询返回TRUE或FALSE。 因此,我的结果属性$ this-> query_result应始终为true或false。

我的问题:

  • 动态显示反馈给用户 后提交表单(提交到同一 页)
  • $这个 - > query_result是真实的,如果它 返回一个字符串

我添加了代码,看看我在做什么(做错了)

这些是功能NS我使用的连接/查询DB:

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; 
    } 

通过返回一个文本字符串,返回结果将始终为真。 从我阅读的内容来看,我应该有一个处理错误/反馈的函数。

这是我目前在我的模板反馈做:

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> 

回答

0

你可以一个特殊字符添加到错误信息中addNewPerson()的开始。调用脚本将使用字符串函数来检测特殊字符(以便它知道有错误)并移除该字符,以便在没有它的情况下显示该消息。你认为这会适合你想要的吗?

2

只有一个提示:编程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) { 
    // ... 
} 
+0

感谢菲尔。我只使用.Net中的try/catch - 基本上只是示例的最后一部分。你为什么要上课?你不能只是从catch里面抛出错误消息吗?嗯......我有点不确定如何使用这个 - 尽管你有一个干净和漂亮的例子(对不起) – Steven 2009-06-10 13:49:33

+1

Steven,他将标准的Exception类加以子类化,主要是因为它们用作不同类型错误的标记。它使您的代码更具可读性和划分性。但没有用处,因为这只会造成一个人无法理解的混乱。 有关相关问题,请参阅http://stackoverflow.com/questions/699372/using-the-right-exception-subclass-in-ruby。 – 2009-06-14 21:11:49

4

我会使用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() 
} 

夫妇的其他东西与你的脚本指出。

  1. 最好使用PDO并准备 声明。
  2. 您还可以使用以下命令确定字符串长度是否为 。
 
$arr = 'Shoan'; 
var_dump(isset($arr[10])); //false 
var_dump(isset($arr[2])); //true 
  • 筛选用于SQL 注射输入/ XSS 之前利用将其推入数据库或 在应用程序中使用它。
  • +0

    这是一个很好的例子。谢谢!是的,我知道。当我提出基础知识时,我会重构我的代码。我首先必须学习PDO以及如何在MySQL中使用预准备语句。我也将筛选器输入发送给数据库。我打算想出最好的办法来做到这一点。 – Steven 2009-06-10 14:07:15

    0

    必须回答我自己的示例以显示代码段。 考虑到Shoan的建议,我试图扩展DAL以使用PDO(class 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();

    但是,一旦我添加'扩展PDO',我的页面变为空白。我也无法使用任何try/catch/throw - 这一切都给我错误消息。