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

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?