有人可以看看这个并告诉我它为什么不起作用。这是我正在研究的课程的一部分。插入查询工作正常,如果我调用$ char-> db-> insert_id;从它外面工作($ char是班级)
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;
}
答案 0 :(得分:2)
尝试在if / else之前移动$this->charID = $this->db->insert_id;
,因为两者都会在到达insert_id
行之前返回。
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';
}
}
答案 1 :(得分:2)
由于return语句在返回发生之前尝试将其放在部件上,因此无法达到insert_id的赋值。
答案 2 :(得分:0)
请尝试以下。
正确引用值:
$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;