我正在编辑从php 5.3到php 7+的旧项目。 令人不快的工作,但我必须对代码进行最少的更改。
我遇到了以下问题。 insert_id始终返回0。
我已经读到这可能是因为我在表上没有auto_increment键,或者上一个查询不是source /etc/profile
或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 7+一起使用
答案 0 :(得分:4)
$this->connection()
每次都会返回 新连接 。插入ID是特定于连接的,否则您将受到并行客户端的干扰。您需要重用连接对象:
$query="some INSERT query";
$con = $this->connection();
$res = $con->query($query);
if ($res) $response = $con->insert_id;
最好在$this->con = $this->connection()
中执行一次__construct
,并在整个对象中重用相同的连接;或者,更好的是,在实例化对象时注入已全局建立的一个连接作为依赖项:
$con = new mysqli(...);
$db = new DBTable($con);
否则,您将有很多开销要不断建立和断开连接。更不用说可测试性和硬编码连接了。
答案 1 :(得分:1)
我也直接使用了您帖子中的代码,尽管上面的答案也很棒。
<?php
class DBTable{
private $dbcon;
function __construct() { //this constructor is called when you do $var = new DBTable() to instantiate your object
//create the connection and assign it to the dbcon var
$this->dbcon = new mysqli('localhost', 'username', 'password', 'db');
//throw connection error and die
if ($this->dbcon->connect_error) {
printf("Connect failed: %s\n", $this->$dbcon->connect_error);
exit();
}
//throw mysql error and die
if (!$this->dbcon->set_charset("utf8")) {
printf("Error loading character set utf8: %s\n", $this->$dbcon->error);
exit();
}
}
//I add a row and return an ID
function addrow_id(){
//create your query string
$query="INSERT INTO TEST() VALUES()";
//run the query
$res = $this->dbcon->query($query);
if ($res){ //if this value evaluates to zero, we want to throw an error
$response = $this->dbcon->insert_id;
} else { //throw an error, because the query came back with a negative val
$error = 'When adding a row, I got no results or a value that php interpolates as negative';
throw new Exception($error);
}
//return the new id
return $response;
}
}
//instantiate your object/class
$dbTable = new DBTable();
//dump the outcome of your adding a row
var_dump($dbTable->addrow_id());
?>