PHP:找出刚刚插入的行数据的主键

时间:2015-12-10 23:23:23

标签: php mysql

我正在尝试找出id值,这是表的主键。为了做到这一点,我实现了这样的代码。

public function addNewPost($userName, $content) {

    // insert post information into the data.
    $query = "INSERT INTO posts(uploader, content, uploaded_at) VALUES('$userName', '$content', NOW())";
    $result = mysqli_query($this->db->connect(), $query);
    $id = mysqli_insert_id($this->db->connect());

    if ($result) {

        // get the row data with the found primary key
        $query_get_row_data = "SELECT * FROM posts WHERE id = '$id'";
        $result_row_data = mysqli_query($this->db->connect(), $query_get_row_data);

        return mysql_fetch_array($result_row_data);
    } else {
        return false;
    }
}

这里我尝试通过运行$id = mysqli_insert_id($this->db->connect());命令获取id,但它似乎不起作用。

任何解决方案?

2 个答案:

答案 0 :(得分:1)

您需要使用连接变量而不是函数调用。第二次调用connect()正在返回一个新连接。

$connection = $this->db->connect();
$result = mysqli_query($connection, $query);
$id = mysqli_insert_id($connection);

或者如果你在db类中保留一个有意义的变量:

$result = mysqli_query($this->db->connection, $query);
$id = mysqli_insert_id($this->db->connection);

答案 1 :(得分:0)

保存连接

public function addNewPost($userName, $content) {

    // insert post information into the data.
    $query = "INSERT INTO posts(uploader, content, uploaded_at) VALUES('$userName', '$content', NOW())";
    $con = $this->db->connect();
    $result = mysqli_query($con, $query);
    $id = mysqli_insert_id($con);

    if ($result) {

        // get the row data with the found primary key
        $query_get_row_data = "SELECT * FROM posts WHERE id = '$id'";
        $result_row_data = mysqli_query($this->db->connect(), $query_get_row_data);

        return mysql_fetch_array($result_row_data);
    } else {
        return false;
    }
}