neoSmith neoSmith - 10 days ago 6
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"]);
break;
case 2: #Guitarist
$ms = new Guitarist($row["id"],$row["name"],$row["band"],$row["dateBirth"]);
break;
case 3: #Drummer
$ms = new Drummer($row["id"],$row["name"],$row["band"],$row["dateBirth"]);
break;
default:
$ret[1] = 3; #Estat de l'operacio, error al array
return $ret;
break;
}
array_push($arrayMusicsObjectes, $ms); #Inserir cada music al array
}


And here comes the real problem, the constructor:

<?php
require_once(__DIR__.'/MusicAbstract.php');

class Drummer extends MusicAbstract{

public function getInstrument(){
return 'Drum';
}

public function __construct($id, $name, $band, $dateBirth){
$this->getId();
$this->setName($name);
$this->setBand($band);
$this->setDateBirth($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

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

$this->getId();

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

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

UPDATE

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