1

I'm foolishly writing OO PHP and each object corresponds to a table in the MySQL database. There's an easy way to load the record into memory, i.e., with something like $this->dbrecord=$result->fetch_assoc();, but if I want to do the opposite and put the array back into the database, there doesn't seem to be an easy way to do this, especially since you can't use parameters for column names, that is to say, something like

$query=$sql->prepare("UPDATE ? SET ?=?");
$query->bind_param("sss", $this->table, $key, $value);
foreach ($dbrecord as $key => $value){
    $query->execute();
}

wouldn't work, so I would have to use unsafe and ugly query-splicing where I put the individual values into a string and then pass the string to the MySQL server.

My question is: is there a way to do this elegantly? If there were something like mysqli_stmt::put_array($array), that would be ideal, but if not, there must be some way to write a general-purpose function that does something like this, right? Something I haven't thought of?

Tatpurusha
  • 111
  • 1
  • 2
    You're after [Object-relational mapping](http://en.wikipedia.org/wiki/Object-relational_mapping). See [Good PHP ORM Library?](http://stackoverflow.com/questions/108699/good-php-orm-library) for suggestions. – eggyal Jan 12 '14 at 22:12
  • Thanks, this is very interesting, and probably what I'll use, but if I wanted to do it myself, is there a way to do it that's relatively simple? I guess not, since ORM libraries exist.. – Tatpurusha Jan 12 '14 at 22:20
  • Honestly, it sort of looks like some of the lightweight frameworks used looped foreach and constructed queries with inline variables themselves! So, I would just be kicking the ball down the field without actually resolving the problem. – Tatpurusha Jan 12 '14 at 22:48
  • 1
    If PHP or even MySQL provided some native function to do it, that's all they'd be doing under the hood too. Ultimately *all programming* is layering one tool upon another in order to obtain a more abstract interface. – eggyal Jan 12 '14 at 23:42
  • True. Well, since the program was already mostly done except for a commit() function, I just wrote one myself. I effectively wrote a custom ORM for this project... if it wasn't a project mostly for my own education, I would feel bad about it. – Tatpurusha Jan 13 '14 at 00:33

0 Answers0