Reputation: 325
Can someone take a look at this and tell me why it's not working. This is part of a class that I'm working on. The insert query works fine and if I call $char->db->insert_id; from outside the class it works ($char being the class)
function createChar($charName, $charRace, $charClass) {
//put userId, charName and charRace into database
$sql="insert into characters (userID, name, race, class) values ('$this->userID', '$charName', '$charRace', '$charClass') ";
$result=$this->db->query($sql);
if($this->db->affected_rows == '1')
{
return '1';
}
else
{
return '0';
}
//get last insert id
$this->charID=$this->db->insert_id;
}
Upvotes: 0
Views: 3200
Reputation: 1220
Try moving $this->charID = $this->db->insert_id;
before the if/else, since both will return before getting to the insert_id
line.
function createChar($charName, $charRace, $charClass) {
//put userId, charName and charRace into database
$sql = "insert into characters (userID, name, race, class) values ('$this->userID', '$charName', '$charRace', '$charClass') ";
$result = $this->db->query($sql);
//get last insert id
$this->charID = $this->db->insert_id;
if($this->db->affected_rows == '1')
{
return '1';
}
else
{
return '0';
}
}
Upvotes: 2
Reputation:
Try below.
quote values properly:
$sql="insert into characters (userID, name, race, class) values
('".$this->userID."', '".$charName."', '".$charRace."','".$charClass."') ";
$result=$this->db->query($sql);
$this->charID=$this->db->insert_id;
Upvotes: 0
Reputation: 802
It can't reach the assigning of the insert_id because of the return statement try to put it on the part before the return happens.
Upvotes: 2