[英]Multi line statement in PHP to MySQL database (resorting auto incremented IDs)
I have a little bit of a problem figuring out where the error comes from. 我有一个问题,找出错误的来源。 The background is that I have a table and using a form I update the values into the table and can update them and delete them using different buttons.
背景是我有一个表,并使用表单将值更新到表中,并且可以使用不同的按钮来更新和删除它们。
This leaves the auto incremented IDs in disorder after deletion and I thought it would be just good practice to see if I could reset the order using a simple button. 删除后,这会使自动递增的ID处于混乱状态,我认为这是一个很好的做法,看看我是否可以使用简单的按钮重置订单。
Otherwise I've been updating them using 否则我一直在使用
SET @num := 0;
UPDATE tableName SET id = @num := (@num+1);
ALTER TABLE tableName AUTO_INCREMENT = 1;
in phpmyadmin. 在phpmyadmin中。 I got it from this answer : Auto Increment after delete in MySQL
我从这个答案中得到的: 在MySQL中删除后自动递增
//resort database
if(isset($_POST['resort'])){
// Database connection opening
$mysqli = NEW MySQLi('localhost','root','','powerstations'); //our server, the username, the password (empty), the database itself
if($mysqli) {
echo "Connected!";
} else {
echo "Problem.";
}
$sql_resort = "SET @num := 0; ";
$sql_resort .= "UPDATE powerdata SET id = @num := (@num+1); ";
$sql_resort .= "ALTER TABLE powerdata AUTO_INCREMENT = 1; ";
if ($mysqli->query($sql_resort) === TRUE) {
echo "Resorted successfully";
} else {
echo "Error: " . $sql_resort . "<br>" . $mysqli->error;
}
$mysqli->close();
The error I get is: SET @num := 0; 我得到的错误是:SET @num:= 0; UPDATE powerdata SET id = @num := (@num+1);
更新powerdata SET id = @num:=(@ num + 1); ALTER TABLE powerdata AUTO_INCREMENT = 1;
ALTER TABLE powerdata AUTO_INCREMENT = 1;
You have an error in your SQL syntax; 您的SQL语法有误; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UPDATE powerdata SET id = @num := (@num+1);
检查与您的MySQL服务器版本相对应的手册以获取正确的语法,以在'UPDATE powerdata SET id = @num:=(@ num + 1)附近使用; ALTER TABLE powerdata AUTO_INCREMENT' at line 1
第1行的ALTER TABLE powerdata AUTO_INCREMENT'
I tried to search for typos by putting the multi line statement into phpmyadmin, but found nothing and I don't see where the problem with the "code structure" is if there is one. 我试图通过将多行语句放入phpmyadmin中来搜索拼写错误,但一无所获,而且我不知道“代码结构”的问题在哪里。
When attempting do execute multiple statements in a single query you have to call $mysqli->multi_query($sql)
not $mysqli->query($sql)
. 尝试在单个查询中执行多个语句时,必须调用
$mysqli->multi_query($sql)
而不是$mysqli->query($sql)
。
So you will need to update 所以你需要更新
if ($mysqli->query($sql_resort) === TRUE) {}
to 至
if ($mysqli->multi_query($sql_resort) === TRUE) {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.