0

I have an object Obj with a method sql() that creates SQL queries to update a database. The tables in the database have unique names for their ID fields. My objective is to be able to define the table name and ID field name in the child object.

class Obj {

  public static function sql(){
    $attributes = ['something', 'else', 'whatever'];
    foreach($attributes as $key => $value){
      $attribute_pairs[] = "{$key}='{$value}'";
    }

   $sql = "UPDATE " . static::$table_name . " SET ";
   $sql .= join(", ", $attribute_pairs);
   $sql .= " WHERE " . static::$id_name . "='" . static::$id_name . "' ";

   return $sql;
 }
}

class ChildObj extends Obj{
  protected static $table_name="accounts";
  protected static $id_name = "account_id";
}

$test = new ChildObj;

echo $test::sql(); 
//returns UPDATE accounts SET 0='something', 1='else', 2='whatever' WHERE account_id='account_id'

The problem with code above is that I have not been able to figure out how to reference the value of the ID field. This line in particular:

$sql .= " WHERE " . static::$id_name . "='" . static::$id_name . "' ";

returns this:

account_id='account_id'

Where I need it to return the value of 'account_id'

account_id='#'
tj12
  • 1
  • In the sql method, why are you doing a foreach and using key and value? According to your example, the generated code will be : ` 0='something', 1='else', 2='whatever' `. Are your sql fields names 0, 1, 2? – Alexey Dec 12 '17 at 23:42
  • Another thing is, where exactly are you going to get the account_id value? From the code you showed, I really can't see how exactly that value will be extracted. – Alexey Dec 12 '17 at 23:44
  • Yes. assume that the field names are 0,1,2. I have another function that generates the field names, but I thought that would add irrelevant code that wasn't addressing my issue. – tj12 Dec 13 '17 at 00:18
  • The account_id value would come from a form where the ChildObj has been instantiated – tj12 Dec 13 '17 at 00:20
  • So are we talking about getting the value from $_POST or $_GET? – Alexey Dec 13 '17 at 07:57
  • Yes. value comes from $_POST – tj12 Dec 13 '17 at 17:42
  • In that case the title of this question doesn't make sense. What do static variables have to do with getting values from POST? – Alexey Dec 13 '17 at 17:57

0 Answers0