我正在编辑一个从php5.3到php7+的老项目。不愉快的工作,但我必须做它与最小的代码更改。
我遇到了以下问题。insert\u id始终返回0。
我读过,这可能是因为我没有表上的自动递增键,或者上一个查询不是 INSERT
或者 UPDATE
但我的问题不是因为这个。请求成功地将信息输入数据库。
代码如下:
class DBTable{
function connection(){
$mysqli = new mysqli('localhost', 'username', 'pass', 'db');
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if (!$mysqli->set_charset("utf8")) {
printf("Error loading character set utf8: %s\n", $mysqli->error);
exit();
}
return $mysqli;
}
function addrow_id($row){
$query="some INSERT query";
$res = $this->connection()->query($query);
if ($res) $response = $this->connection()->insert_id; //always returns zero
return $response;
}
}
我很清楚这不是个好主意 PHP
但是我不能从一个新的项目开始,我的任务就是使用PHP7+
2条答案
按热度按时间pxq42qpu1#
我直接使用了你帖子中的代码,尽管上面的答案也很好。
xurqigkl2#
$this->connection()
每次返回一个新连接。插入ID是特定于连接的,否则会受到并行客户端的干扰。您需要重用连接对象:最好是你做的
$this->con = $this->connection()
一次__construct
并在整个对象中重复使用相同的连接;或者,更好的做法是,在示例化对象时,注入一个全局建立的连接作为依赖关系:否则,经常建立和断开连接会产生大量开销。更不用说硬编码连接的可测试性等了。