mysql insert\u id总是返回零

c9qzyr3d  于 2021-06-23  发布在  Mysql
关注(0)|答案(2)|浏览(351)

我正在编辑一个从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+

pxq42qpu

pxq42qpu1#

我直接使用了你帖子中的代码,尽管上面的答案也很好。

<?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());
?>
xurqigkl

xurqigkl2#

$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);

否则,经常建立和断开连接会产生大量开销。更不用说硬编码连接的可测试性等了。

相关问题