我的查询中有一些错误的语法,我试图创建“prev_id”以拉入 $row 结果链接。关于更好的方法有什么想法吗?
编辑:错误是“检查与您的 MySQL 服务器版本相对应的手册,了解在‘prev_id’附近使用的正确语法。”
function traversePhoto($the_selected_id) {
global $pdo;
$id = $the_selected_id;
$stmt_a = $pdo->prepare("
(SELECT * FROM images WHERE id < '.intval($id).' ORDER BY id DESC LIMIT 1)
UNION (SELECT * FROM images WHERE id = (SELECT MAX(id) FROM images)) LIMIT 1 prev_id");
$stmt_b = $pdo->prepare("
(SELECT * FROM images WHERE id > '.intval($id).' ORDER BY id ASC LIMIT 1)
UNION (SELECT * FROM images WHERE id = (SELECT MIN(id) FROM images)) LIMIT 1 next_id");
// $vars = array(':id' => $id);
$prev = $stmt_a->execute();
$next = $stmt_b->execute();
if ($prev) {
while($row = $stmt_a->fetchObject()) {
echo '<a href="' . $row['prev_id'] . '">Previous</a>';
}
} else {
echo 'no previous';
}
if ($next) {
while($row = $stmt_b->fetchObject()) {
echo '<a href="' . $row['next_id'] . '">Next</a>';
}
} else {
echo 'no next';
}
}
像这样尝试一下
<?php function traversePhoto($the_selected_id) {
global $pdo;
$id = $the_selected_id;
$stmt_a = $pdo->prepare("
(SELECT * FROM images WHERE id < ? ORDER BY id DESC LIMIT 1)
UNION (SELECT * FROM images WHERE id = (SELECT MAX(id) FROM images)) LIMIT 1");
$stmt_b = $pdo->prepare("
(SELECT * FROM images WHERE id > ? ORDER BY id ASC LIMIT 1)
UNION (SELECT * FROM images WHERE id = (SELECT MIN(id) FROM images)) LIMIT 1");
// $vars = array(':id' => $id);
$prev = $stmt_a->execute(array( (int)$id ));
$next = $stmt_b->execute(array( (int)$id ));
if ($stmt_a->rowCount() > 0) {
while($row = $stmt_a->fetch(PDO::FETCH_ASSOC)) {
echo '<a href="' . $row['prev_id'] . '">Previous</a>';
}
} else {
echo 'no previous';
}
if ($stmt_b->rowCount() > 0) {
while($row = $stmt_b->fetch(PDO::FETCH_ASSOC)) {
echo '<a href="' . $row['next_id'] . '">Next</a>';
}
} else {
echo 'no next';
}
<?php
// Veritabanı bağlantısı (PDO kullanımı)
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Geçerli satırın ID'si (örneğin, 5)
$current_id = 5;
// Önceki satır
$prev_sql = "SELECT * FROM your_table WHERE id < :current_id ORDER BY id DESC LIMIT 1";
$prev_stmt = $pdo->prepare($prev_sql);
$prev_stmt->bindParam(':current_id', $current_id, PDO::PARAM_INT);
$prev_stmt->execute();
$prev_row = $prev_stmt->fetch(PDO::FETCH_ASSOC);
// Sonraki satır
$next_sql = "SELECT * FROM your_table WHERE id > :current_id ORDER BY id ASC LIMIT 1";
$next_stmt = $pdo->prepare($next_sql);
$next_stmt->bindParam(':current_id', $current_id, PDO::PARAM_INT);
$next_stmt->execute();
$next_row = $next_stmt->fetch(PDO::FETCH_ASSOC);
// Sonuçları gösterme
if ($prev_row) {
echo "Önceki Satır: " . $prev_row['column_name'] . "<br>";
} else {
echo "Önceki satır bulunamadı.<br>";
}
if ($next_row) {
echo "Sonraki Satır: " . $next_row['column_name'] . "<br>";
} else {
echo "Sonraki satır bulunamadı.<br>";
}