Php 如何将SQL表:ID重新排列为最后一个ID

Php 如何将SQL表:ID重新排列为最后一个ID,php,mysql,html-table,Php,Mysql,Html Table,我有个问题;我的数据库中有一个名为items的表,其内容包括id,allowComments,fromUserId,category,categoryttle,price,likescoount,imagesCount,viewsCount,reviewsCount等 我希望能够将我所需的id重新排列为最新的id,并将其余的向上携带 下面是一个例子: id allowComments fromUserId category categoryTitle price 1

我有个问题;我的数据库中有一个名为items的表,其内容包括
id
allowComments
fromUserId
category
categoryttle
price
likescoount
imagesCount
viewsCount
reviewsCount

我希望能够将我所需的
id
重新排列为最新的
id
,并将其余的向上携带

下面是一个例子:

id  allowComments   fromUserId  category    categoryTitle     price

1        1              1          3            Phone         20000
2        1              1          5            Car           100000
3        1              5          2            Console       20000
4        1              2          1            Fashion       100
5        0              1          3            Phone         12000
6        1              2          3            Phone         21300
等等

所以我的问题是,如何使用PHP使
id
3
成为最后一个
id
,并对其他id进行排序以有序地向上移动

假设这是我从数据库中获取内容的php文件

                                <th>Id</th>
                                <th>category</th>
                                <th>price</th>
                                <th>cATEGORY ID </th>
                                <th>fromUserId</th>
                                <th>EDIT </th>
                                <th>REFRESH </th>

                            </tr>

                            <?php $k=1; while($get=mysql_fetch_array($insertionquery)) {?>

<td><?php echo $get['id'];?></td>
<td><?php echo $get['categoryTitle'];?></td>
    <td><?php echo $get['price']; ?></td>
    <td><?php echo $get['category']; ?></td>
    <td><?php echo $get['fromUserId']; ?></td>

<td><a href="editmenu.php?EDITC=<?php echo $get['id']?>"></a></td>
<td><a href="refresh.php?REFRESH=<?php echo $get['id']?>"></a></td>
Id
类别
价格
类别ID
fromUserId
编辑
刷新

好的,在下面的代码中,我将对您需要了解的所有内容进行注释。这是很重要的,你读这篇文章,让你了解它是如何运作的!我还将给您留下这个链接:这样您就可以在一个更加用户友好的环境中了解更多关于PDO和准备好的语句的信息。在这个问题的底部,您可以找到没有所有注释的代码,以使其更加清晰

请记住,您需要在代码顶部设置正确的数据库信息

注释中有解释的代码:

<?php

/* Database info */
$dbhost = 'localhost';
$dbuser = '';
$dbpass = '';
$dbname = 'globali2_olx';

/* First we set up some information for our PDO object */
$dsn = 'mysql:host=' . $dbhost . ';dbname=' . $dbname;
$options = array(
    PDO::ATTR_PERSISTENT    => true,
    PDO::ATTR_ERRMODE       => PDO::ERRMODE_EXCEPTION
);

/* Next we try to instantiate the PDO object and see if we can connect to the database */
try{
    $pdo = new PDO($dsn, $dbuser, $dbpass, $options);
}
/* Here we'll catch any database connection errors and output them so we know what's going on */
catch(PDOException $e){
    $error = $e->getMessage();
    return $error;
    exit;
}

/* Now lets try to change row id 3 to the last row id */

/* First we setup our query */
$query = 'UPDATE items SET id=(SELECT max(id)+1) FROM items WHERE id = :id';

/* As you can see, we don't have the number 3 in there. Instead, we have a
   placeholder ':id'. This is because we're going to use Prepared Statements.
   They are not needed for this case, but I want to show how to do this
   because you do need them if you want to insert data that's provided by a user.
   This is to prevent SQL injection. SQL injection is very easy and allows
   visitors to your website to completely delete your database if you don't
   protect yourself against it. This will do just that. */

/* So lets prepare our query first */
$stmt = $pdo->prepare($query);

/* Set ID */
$id = 3;

/* Now we're going to bind the data to the placeholder */
$stmt->bindParam(':id', $id, PDO::PARAM_INT);

/* Now all that's left to do is execute it so our database gets updated */
try {
    $stmt->execute();
}
/* Again, catch any errors in our query and output them */
catch(PDOException $e){
    $error = $e->getMessage();
    return $error;
    exit;
}

/* Next we need to re-arrange the id's */

/* First we setup our query */
$query = 'ALTER TABLE items AUTO_INCREMENT = 1';

/* Again, Prepared Statements are not nessesary here. So I'm gonna show
   you how to do it without them. */

/* All we have to do is query the database directly */
try {
    $pdo->query($query);
}
/* Again, catch any errors in our query and output them */
catch(PDOException $e){
    $error = $e->getMessage();
    return $error;
    exit;
}

?>
<?php

/* Database info */
$dbhost = 'localhost';
$dbuser = '';
$dbpass = '';
$dbname = 'globali2_olx';

/* Set DSN and Options */
$dsn = 'mysql:host=' . $dbhost . ';dbname=' . $dbname;
$options = array(
    PDO::ATTR_PERSISTENT    => true,
    PDO::ATTR_ERRMODE       => PDO::ERRMODE_EXCEPTION
);

/* Instantiate the PDO object */
try{
    $pdo = new PDO($dsn, $dbuser, $dbpass, $options);
}
catch(PDOException $e){
    $error = $e->getMessage();
    return $error;
    exit;
}

/* Set query */
$query = 'UPDATE items SET id=(SELECT max(id)+1) FROM items WHERE id = :id';

/* Prepare query */
$stmt = $pdo->prepare($query);

/* Set ID */
$id = 3;

/* Bind values */
$stmt->bindParam(':id', $id, PDO::PARAM_INT);

/* Execute query */
try {
    $stmt->execute();
}
catch(PDOException $e){
    $error = $e->getMessage();
    return $error;
    exit;
}

/* Set query */
$query = 'ALTER TABLE items AUTO_INCREMENT = 1';

/* Query database */
try {
    $pdo->query($query);
}
catch(PDOException $e){
    $error = $e->getMessage();
    return $error;
    exit;
}

?>

清除代码:

<?php

/* Database info */
$dbhost = 'localhost';
$dbuser = '';
$dbpass = '';
$dbname = 'globali2_olx';

/* First we set up some information for our PDO object */
$dsn = 'mysql:host=' . $dbhost . ';dbname=' . $dbname;
$options = array(
    PDO::ATTR_PERSISTENT    => true,
    PDO::ATTR_ERRMODE       => PDO::ERRMODE_EXCEPTION
);

/* Next we try to instantiate the PDO object and see if we can connect to the database */
try{
    $pdo = new PDO($dsn, $dbuser, $dbpass, $options);
}
/* Here we'll catch any database connection errors and output them so we know what's going on */
catch(PDOException $e){
    $error = $e->getMessage();
    return $error;
    exit;
}

/* Now lets try to change row id 3 to the last row id */

/* First we setup our query */
$query = 'UPDATE items SET id=(SELECT max(id)+1) FROM items WHERE id = :id';

/* As you can see, we don't have the number 3 in there. Instead, we have a
   placeholder ':id'. This is because we're going to use Prepared Statements.
   They are not needed for this case, but I want to show how to do this
   because you do need them if you want to insert data that's provided by a user.
   This is to prevent SQL injection. SQL injection is very easy and allows
   visitors to your website to completely delete your database if you don't
   protect yourself against it. This will do just that. */

/* So lets prepare our query first */
$stmt = $pdo->prepare($query);

/* Set ID */
$id = 3;

/* Now we're going to bind the data to the placeholder */
$stmt->bindParam(':id', $id, PDO::PARAM_INT);

/* Now all that's left to do is execute it so our database gets updated */
try {
    $stmt->execute();
}
/* Again, catch any errors in our query and output them */
catch(PDOException $e){
    $error = $e->getMessage();
    return $error;
    exit;
}

/* Next we need to re-arrange the id's */

/* First we setup our query */
$query = 'ALTER TABLE items AUTO_INCREMENT = 1';

/* Again, Prepared Statements are not nessesary here. So I'm gonna show
   you how to do it without them. */

/* All we have to do is query the database directly */
try {
    $pdo->query($query);
}
/* Again, catch any errors in our query and output them */
catch(PDOException $e){
    $error = $e->getMessage();
    return $error;
    exit;
}

?>
<?php

/* Database info */
$dbhost = 'localhost';
$dbuser = '';
$dbpass = '';
$dbname = 'globali2_olx';

/* Set DSN and Options */
$dsn = 'mysql:host=' . $dbhost . ';dbname=' . $dbname;
$options = array(
    PDO::ATTR_PERSISTENT    => true,
    PDO::ATTR_ERRMODE       => PDO::ERRMODE_EXCEPTION
);

/* Instantiate the PDO object */
try{
    $pdo = new PDO($dsn, $dbuser, $dbpass, $options);
}
catch(PDOException $e){
    $error = $e->getMessage();
    return $error;
    exit;
}

/* Set query */
$query = 'UPDATE items SET id=(SELECT max(id)+1) FROM items WHERE id = :id';

/* Prepare query */
$stmt = $pdo->prepare($query);

/* Set ID */
$id = 3;

/* Bind values */
$stmt->bindParam(':id', $id, PDO::PARAM_INT);

/* Execute query */
try {
    $stmt->execute();
}
catch(PDOException $e){
    $error = $e->getMessage();
    return $error;
    exit;
}

/* Set query */
$query = 'ALTER TABLE items AUTO_INCREMENT = 1';

/* Query database */
try {
    $pdo->query($query);
}
catch(PDOException $e){
    $error = $e->getMessage();
    return $error;
    exit;
}

?>

测试上述脚本不起作用,因此我进行了调查,发现有问题。使用下面的代码,我测试了它,它工作了

<?php

/* Database info */
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'globali2_olx';

/* Set DSN and Options */
$dsn = 'mysql:host=' . $dbhost . ';dbname=' . $dbname;
$options = array(
PDO::ATTR_PERSISTENT    => true,
PDO::ATTR_ERRMODE       => PDO::ERRMODE_EXCEPTION
);

/* Instantiate the PDO object */
try{
    $pdo = new PDO($dsn, $dbuser, $dbpass, $options);
}
catch(PDOException $e){
    $error = $e->getMessage();
    return $error;
    exit;
}

/* Set ID */
$id = 25;

/* Set query */

$query = "update location j1 inner join location j2 on j1.id <= j2.id 
 left outer join location j3 on j2.id < j3.id 
 set j1.id = j2.id + 1 
 where j1.id = $id and j3.id is null";

/* Prepare query */
$stmt = $pdo->prepare($query);

/* Bind values */
$stmt->bindParam(':id', $id, PDO::PARAM_INT);

/* Execute query */
try {
    $stmt->execute();
}
catch(PDOException $e){
    $error = $e->getMessage();
    return $error;
    exit;
}

/* Set query */
$query = 'ALTER TABLE location AUTO_INCREMENT = 1';

/* Query database */
try {
    $pdo->query($query);
}
catch(PDOException $e){
    $error = $e->getMessage();
    return $error;
    exit;
}

?>

或者您可以使用这个简单的代码

<?php


include_once($_SERVER['DOCUMENT_ROOT']."/config/config.php");

// Create connection
$con = mysqli_connect($host, $user, $pass, $database);


 $id = 128;

$Sql_Query = "update product set id=3 where id=1";

$Sql_Query = "update product j1 inner join product j2 on j1.id <= j2.id 
 left outer join product j3 on j2.id < j3.id 
 set j1.id = j2.id + 1 
 where j1.id = $id and j3.id is null";

 if(mysqli_query($con,$Sql_Query))
{
 echo 'Record Updated Successfully';
}
else
{
 echo 'Something went wrong';
 }

 mysqli_close($con);
?>

研究代码并使用最适合您的代码。修改表格,一切都会正常工作

UPDATE jobs j1
INNER JOIN jobs j2 ON j1.worker_id <= j2.worker_id 
LEFT OUTER JOIN jobs j3 ON j2.worker_id < j3.worker_id 
SET j1.worker_id = j2.worker_id + 1 
WHERE j1.worker_id = 3 AND j3.worker_id IS NULL;
更新作业j1
j1.worker\u id上的内部联接作业j2创建表作业(id串行主键,worker\u id int);
mysql>将值(1)、(2)、(3)、(4)、(5)插入作业(worker_id);
mysql>从作业中选择*;
+----+-----------+
|id |工人id|
+----+-----------+
|  1 |         1 |
|  2 |         2 |
|  3 |         3 |
|  4 |         4 |
|  5 |         5 |
+----+-----------+
mysql>在j1上更新作业j1内部连接作业j2。工人id从作业中选择*;
+----+-----------+
|id |工人id|
+----+-----------+
|  1 |         1 |
|  2 |         2 |
|  3 |         6 |
|  4 |         4 |
|  5 |         5 |
+----+-----------+
无论我们要更改的值是多少,它都可以工作:

mysql> update jobs j1 inner join jobs j2 on j1.worker_id <= j2.worker_id 
 left outer join jobs j3 on j2.worker_id < j3.worker_id 
 set j1.worker_id = j2.worker_id + 1 
 where j1.worker_id = 5 and j3.worker_id is null;

mysql> select * from jobs;
+----+-----------+
| id | worker_id |
+----+-----------+
|  1 |         1 |
|  2 |         2 |
|  3 |         6 |
|  4 |         4 |
|  5 |         7 |
+----+-----------+
mysql>更新作业j1内部连接作业j1上的作业j2.worker\u id从作业中选择*;
+----+-----------+
|id |工人id|
+----+-----------+
|  1 |         1 |
|  2 |         2 |
|  3 |         6 |
|  4 |         4 |
|  5 |         7 |
+----+-----------+
即使我们正在更改表中已具有最高值的行,它也会起作用:

mysql> update jobs j1 inner join jobs j2 on j1.worker_id <= j2.worker_id 
 left outer join jobs j3 on j2.worker_id < j3.worker_id 
 set j1.worker_id = j2.worker_id + 1 
 where j1.worker_id = 7 and j3.worker_id is null;

mysql> select * from jobs;
+----+-----------+
| id | worker_id |
+----+-----------+
|  1 |         1 |
|  2 |         2 |
|  3 |         6 |
|  4 |         4 |
|  5 |         8 |
+----+-----------+
mysql>更新作业j1内部连接作业j1上的作业j2.worker\u id从作业中选择*;
+----+-----------+
|id |工人id|
+----+-----------+
|  1 |         1 |
|  2 |         2 |
|  3 |         6 |
|  4 |         4 |
|  5 |         8 |
+----+-----------+

对于数据库来说,移动id通常被认为是一个坏主意,不如改为添加一个排序列?首先将id设置为最后一个id:
更新表\u name set id=(从表\u name中选择max(id)+1),其中id=3。接下来重置自动增量计数器:
ALTER TABLE TABLE\u name auto\u increment=1
能否请您以php文件的形式编写代码我有点困惑,因为我不知道您使用的是PDO还是MySQLi。您没有提供任何代码。我也不知道你的桌子名。如果你能告诉我这些信息,我可以为您编写一些示例代码。我遇到这样的错误:无法在第33行的C:\xampp\htdocs\kobobay\admin\refresh.php中通过引用传递参数2是$stmt->bindParam(':id',3)@麦克爵士,现在该修好了。@麦克爵士,或者现在该修好了。我忘了修复这两个代码。我的不好。谢谢你的回复。它停止显示错误,但它不会在数据库中重新排列id。还是一样,请回复。代码没有更新或重新排列sql?