我正在建立一个网站,我想在Bootstrap轮播中显示用户评论。我想只显示最新的3条反馈。最新的评论必须有一个“活跃”的类。为了做到这一点,我不仅在插入表格后,而且在整个网站中都需要最后一个ID。到目前为止我试过这个:
$sql = "SELECT MAX(id) FROM comments";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$last_id = $row["id"];
}
我知道有一种方法可以在插入新行后获取last_id,但我总是需要最后一个变量。任何人都可以帮我这个吗?
答案 0 :(得分:2)
SELECT id FROM `comments` order by id desc limit 1
当你在结果中使用SELECT MAX(id) FROM comments
字段名时,将是MAX(id)和$ row [“id”];将无法正常工作
如果您想使用MAX,请使用类似SELECT MAX(id) as id FROM comments
答案 1 :(得分:0)
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
if (mysqli_query($conn, $sql)) {
//I guess this is the line you're lookin for
$last_id = mysqli_insert_id($conn);
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}