所以, 我在这个网站上找到了这个脚本: http://www.webdesignerforum.co.uk/topic/15011-moving-rows-in-a-database-up-or-down-with-php/
并且我想我会尝试重写它以便与Mysqli一起使用。
但是,我对SQL Querys并不是很强大,而且我目前正在努力研究如何完成脚本的最后一部分,这是你再次将值插入数据库的最后一部分。
到目前为止,我已经设法改写了第一部分,或者至少我认为我已经改写了。
<?php
$mysqli = new mysqli("localhost", "name", "password", "db");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$result = $mysqli->query("SELECT min(pos) FROM category");
$row = $result->fetch_row();
$minOrder = $row[0];
$result = $mysqli->query("SELECT max(pos) FROM category");
$row = $result->fetch_row();
$maxOrder = $row[0];
$result = $mysqli->query("select * from category order BY pos asc");
$news=$result;
while ($row = $news->fetch_assoc()) {
$order = $row['pos'];
$name = $row['navn'];
echo "Name $name:<br>";
if($order > $minOrder) { // was $up, can be optimised??
$tmp_up = $order-1;
echo "<a href=\"move_cat.php?a=$order&b=$tmp_up\">Move Up</a>";
}
if($order < $maxOrder) { // was $down, can be optimised??
$tmp_down = $order+1;
echo "<a href=\"move_cat.php?a=$order&b=$tmp_down\">Move Down</a>";
}
}
$mysqli->close();
?>
我认为这部分是可以的,但接下来的部分是我正在讨论的部分:
<?php
include("config.php");
$a = $_GET["a"];
$b = $_GET["b"];
/* Check numeric --- this is stronger than just isset and ensures no SQL injection occurs */
if (is_numeric($a) && is_numeric($b)) {
$result = mysql_query("UPDATE links SET `order`=(CASE `order` WHEN $a THEN $b ELSE $a END) WHERE `order`=$a OR `order`=$b", $db);
}
/* Always redirect back using HTTP response */
header("Location: links2.php");
?>
这是我需要帮助重写的那个,我不知道,我将如何将Prepared Statements与这样的SQL查询一起使用。
希望这一切都是可以理解的,如果不是,请不要犹豫:)
答案 0 :(得分:0)
使用您当前的UPDATE
声明:
$update = $mysqli->prepare('
UPDATE links
SET `order`=(CASE `order` WHEN ? THEN ? ELSE ? END)
WHERE `order`=? OR `order`=?
');
$update->bind_param('iiiii', $a, $b, $a, $a, $b);
$update->execute();
但是,我很想做更像这样的事情(允许人们将项目移动到任意数量的地方):
$update = $mysqli->prepare('
UPDATE links
SET `order`= `order` '.($a < $b ? '+' : '-').' 1
WHERE `order` BETWEEN ? AND ?
');
$update->bind_param('ii', min($a,$b), max($a,$b));
$update->execute();