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条)

报告相同问题?

悬赏问题

  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗