dongse7261 2018-04-27 20:05
浏览 57
已采纳

PHP - 带SQL查询的构造函数[关闭]

Option 1: query the data first and then pass the data to the constructor

Option 2: use the constructor to query the data and then fill the properties


Option 1 Example

$val1 = 1;
$query = mysql_query("SELECT val2, val3, val4 FROM table WHERE val1 = '".$val1."'");
$row = mysql_fetch_assoc($query);
$o = new Class($row['val1'], $row['val2'], $row['val3'], $row['val4']);

Option 2 Example

$val1 = 1;
$o = new Class($val1);

// in Class constructor
public function __construct($val1) {
    $query = mysql_query("SELECT val2, val3, val4 FROM table WHERE val1 = '".$val1."'");
    $row = mysql_fetch_assoc($query);
    $this->val1 = $row['val1'];
    $this->val2 = $row['val2'];
    // etc ...
}

NOTES

I am perfectly aware that mysql_query is deprecated. Please resist the overwhelming urge to tell me that and contact my PM instead.

I am asking if Option 2 is bad practice or if there are any foreseen predicaments that are overwhelmingly known in the object oriented space. It seems to be the cleaner option to me.

  • 写回答

2条回答 默认 最新

  • douyigua5381 2018-04-27 20:24
    关注

    Show this to whoever is in charge. enter image description here


    But anyways back to your question.

    As much as I hate to answer like this, I think option 2 definitely makes the code cleaner, but you can also make it even more clean, by creating a method in the class that returns what you're looking for.

    <?php
    
    class SomeName extends DBClass
    {
        // No need for the construct in this case
    
        public function fetchResults($val)
        {
            $notSoDirtyVal = mysql_real_escape_string($val);
    
            $query = "SELECT val2, val3, val4 FROM table WHERE val1 = '".$notSoDirtyVal."'"// Make sure you escape, sanitize, and clean this!!!!!
    
            $stmt = mysql_query($query); 
    
            $results = mysql_fetch_assoc($query);
    
            return $results;
        }
    }
    ?>
    

    On your other file you can then do this

    <?php
    $value1 = 1;
    
    $o = new SomeName;
    $results = $o->fetchResults($value1);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里