neoSmith neoSmith - 1 year ago 97
MySQL Question

How not to use set for ID but need it for constructor of Object

I'm trying to make a project where I have a DataBase with Mysql, and I'm adding and updating/deleting data from it.

The thing is, I'm supposed not to use a set for the ID, because I'm using AUTO_INCREMENT when I make the INSERT into de DB.

Then, because of that, when I get back the data from de DB I convert it to an array of objects, but I don't know how to do it without using the setId(). Well, maybe with the code you'll understand more what I'm trying to say.

This is how I send the INSERT into the DB (This code is at the controller):

// prepare and bind
$stmt = $conn->prepare("INSERT INTO db_musics (name, band, dateBirth, type)
VALUES (?, ?, ?, ?)");
$stmt->bind_param("sssi", $name, $band, $dateBirth, $type);

Then the problem with converting the returned array from DB into the appropiate object (this is part of the code from the function to get the DB):

while($row = mysqli_fetch_assoc($result)) {
switch ($row["type"]) {
case 1: #Vocalist
$ms = new Vocalist($row["id"],$row["name"],$row["band"],$row["dateBirth"]);
case 2: #Guitarist
$ms = new Guitarist($row["id"],$row["name"],$row["band"],$row["dateBirth"]);
case 3: #Drummer
$ms = new Drummer($row["id"],$row["name"],$row["band"],$row["dateBirth"]);
$ret[1] = 3; #Estat de l'operacio, error al array
return $ret;
array_push($arrayMusicsObjectes, $ms); #Inserir cada music al array

And here comes the real problem, the constructor:


class Drummer extends MusicAbstract{

public function getInstrument(){
return 'Drum';

public function __construct($id, $name, $band, $dateBirth){

So here at the constructor, I get the $id but how can I put it into the object?

Hope I have explained myself properly (English is not my mother language).

Thanks in advance ! :D

Answer Source

Why are you trying to getId() in constructor instead of setting it?


shouldn't it be replaced with $this->setId() ?

Of course if you have setId() method in your model


so if you dont need to use setId() method, simply remove this line and simply attach property this way: $this->id = $id

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download