Skip to content
Advertisement

PHP – constructor with SQL query [closed]

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. These are the reqs for the project.

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.

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement