gpt4 book ai didi

php - 插入查询后,mysqli_insert_id()在同一连接上返回0

转载 作者:行者123 更新时间:2023-11-30 23:44:31 25 4
gpt4 key购买 nike

在你问之前,我已经使用了堆栈溢出和谷歌的搜索功能!

在我的代码中,mysqli_insert_id始终返回0。

在我的“模型” -PHP-Class中,保存函数如下所示:

$result = DB::q($sql);

if(!$result)
{
throw new Exception("Error:".mysqli_error(DB::getDB()));
}
else
{
if(is_null($this->id))
{
$this->id = DB::insert_id();
}
}

$this->update();


我的Class DB看起来像这样:

class DB
{
public static $db = null;

public static function q($sql)
{
self::checkDB();

if(!isset($sql) OR $sql == null OR $sql == "")
{
throw new Exception("\$sql may not be empty");
}
else
{
$result = mysqli_query(self::$db, $sql);
if(!$result)
{
error_log($sql);
throw new Exception(mysqli_error(self::$db));
die();
}

return new DBResult($result);
}
}

public static function checkDB()
{
if(is_null(self::$db))
{
self::$db = mysqli_connect(DB_PORT, DB_USERNAME, DB_PASSWORD, DB_DATABASE);

if(!self::$db)
{
throw new Exception(mysqli_error(self::db));
}
}
}

public static function insert_id()
{
return mysqli_insert_id(self::$db);
}
}

class DBResult
{
private $result = null;

public function __construct($result)
{
$this->result = $result;
}

public function fetch_assoc()
{
return mysqli_fetch_assoc($this->result);
}

public function fetch_object()
{
return mysqli_fetch_object($this->result);
}

public function __get($willget)
{
if($willget == "num_rows")
{
return mysqli_num_rows($this->result);
}
else
{
return $this->result;
}
}
}


当我直接在同一数据库中的服务器上执行多查询时,它将正常工作:

INSERT INTO users (name, age) VALUES ('personA', 42); SELECT last_insert_id() as k;


我还在我的 AUTO_INCREMENT列上设置了 id标志。

在任何查询之间的代码中似乎也没有位置,我将覆盖 $db类中的 DB

非常感谢你的帮助!

最佳答案

问题:
在模型类中有这段代码:

if(is_null($this->id))
{
$this->id = DB::insert_id();
}


由于某些原因,我不知道为什么, $this->id不为null。取而代之的是0。
所以我要做的就是将其更改为

if(empty($this->id))
{
$this->id = DB::insert_id();
}


感谢@Syscall。您帮助我调试了这段代码。很抱歉这个愚蠢的问题,但是我想你们当中有些人知道。整日编程,但作为一种爱好,将无济于事。

关于php - 插入查询后,mysqli_insert_id()在同一连接上返回0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48955641/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com