一直试图获取 SCOPE_IDENTITY()(插入到数据库中的最后一个 ID)并将其作为变量存储在我的 PHP 函数中。
查看了我可能在 stackoverflow 上找到的所有答案,但我仍然没有设法到达那里。
这是我目前拥有的:
// Confirm booking (update database) function
public function insert_userPost($conn)
{
// SQL INSERT command
$sql = ("
INSERT INTO userPost (content, submitted, emotion)
VALUES ('$this->post', 'NOW()', '$this->emotion');
");
if ($conn->query($sql) === TRUE)
{
//echo "success";
$sql = ("SELECT SCOPE_IDENTITY() as Id");
$result = $conn->query($sql);
echo $result;
//header('Location: feed.php?filter=all&page=1');
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
Run Code Online (Sandbox Code Playgroud)
我做错了什么?
编辑:
另外...在构造中,我试图在 $this->post 中传递 Id ($this->Id) 但它返回 0。我可以看到这是由于我只设置 $ this->Id 查询通过后,因此返回 0,但我不确定如何继续。有什么建议?
// Construct
public function __construct($content, $emotion, $conn)
{
$this->content = $content;
$this->emotion = $emotion;
$this->post =
"<div id=\'post\'>
<div id=\'postContent\'>
<p><b>I\'m $this->emotion because</b> $this->Id $this->content<span class=\'emot\'id=\'$this->emotion\'></span></p>
</div>
<div id=\'postInfo\'>
<span class=\'postRelate\' title=\'Click to relate +1\'><p><b>relate</b> (0)</p></span>
<span class=\'postSubmitted\'><p>submitted X minutes ago</p></span>
</div>
</div>";
}
// Confirm booking (update database) function
public function insert_userPost($conn)
{
// SQL INSERT command
$sql = ("INSERT INTO userPost (content, submitted, emotion)
VALUES ('$this->post', NOW(), '$this->emotion')");
if ($conn->query($sql) === TRUE)
{
//echo "success";
echo $this->Id = $conn->insert_id;
//header('Location: feed.php?filter=all&page=1');
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
Run Code Online (Sandbox Code Playgroud)
首先,您的问题被标记为mysql,但是SCOPE_IDENTITY()是 SQL Server 函数。话虽如此,您的代码包含$conn->error,所以我假设您使用的是带有 MySQLi 扩展的 MySQL。
相当于 SQL Server 的 MySQLSCOPE_IDENTITY()是LAST_INSERT_ID()。但是调用它需要额外的查询,既麻烦又慢。
相反,建议您为此使用内置的 MySQLi 功能,即连接实例的$insert_id属性:
$id = $conn->insert_id;
Run Code Online (Sandbox Code Playgroud)
大多数 SQL 库都有一个内置的功能。如果您使用 PDO 作为您的数据库抽象层,您可以类似地使用PDO::lastInsertId():
$id = $pdo->lastInsertId();
Run Code Online (Sandbox Code Playgroud)
这对 SQL Server 和 MySQL(以及其他)都适用。