0

我不确定在向最终用户提供 READABLE 反馈时最好使用哪种方法。我已经阅读了一些论坛,但并没有真正变得更明智(或者我没有理解它)

我想在插入/更新失败、成功以及提供自定义反馈时提供反馈(例如检查项目是否已经存在)。

在 INSERT、UPDATE、DELETE、DROP 等操作中,查询返回 TRUE 或 FALSE。因此,我的结果属性$this->query_result应该始终为真或假。

我的问题:

  • 表单提交后动态显示反馈给用户(提交到同一页面)
  • $this->query_result 如果返回一个字符串则为真

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

这些是我用于连接/查询数据库的函数:

  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>
4

4 回答 4

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 = '肖恩';
var_dump(isset($arr[10])); //错误的
var_dump(isset($arr[2])); //真的
  1. 在将输入推送到数据库或在应用程序中使用之前,过滤输入以进行 sql 注入/XSS 攻击。
于 2009-06-10T13:46:09.623 回答
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) {
    // ...
}
于 2009-06-10T13:26:30.990 回答
0

必须回答我自己的示例以显示代码片段。接受 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 = new DAL();
$myDB->connect();
$result = $myDB->getSomeData();

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

于 2009-06-12T14:06:12.977 回答
0

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

于 2009-06-10T13:25:49.023 回答