添加将id复制到另一行

时间:2018-03-06 13:03:42

标签: php mysql

我有一个代码可以执行此查询并按预期工作:

INSERT INTO items (name) VALUES (\'TEC TEST !"#!12\')

但是当我将这一行添加到它的末尾时,它会失败:

; SELECT @last_id := MAX(id) FROM ".$table_name."; UPDATE ".$table_name." SET sortingId = id WHERE id = @last_id;

我搜遍了谷歌和stackoverflow,但无法找到符合我问题的任何案例:(

我的php调用代码是:

$table_name = $this->_request['table']; 
$data = $this->_request['data'];

$sql0 = "INSERT INTO ".$table_name." (";
$sql1 = " VALUES (";
foreach($data as $key=>$value){
    $sql0 .= $key.",";
    if(is_array($value)) { 
        if($value[1] == 'date')             
            $sql1 .=  $this->db_escape($value[0]).",";
        if($value[1] == 'float')
            $sql1 .= $value.",";
    }else 
        $sql1 .= $this->db_escape($value).",";
}
$sql0 = substr($sql0, 0, -1).")";
$sql1 = substr($sql1, 0, -1).")";
$sql2 = "SELECT @last_id := MAX(id) FROM items; UPDATE items SET sortingId = id WHERE id = @last_id;";

$string = stripslashes($sql0.$sql1.$sql2);

$sql = mysqli_query($this->db, $sql0.$sql1.$sql2);
if(mysqli_insert_id($this->db) > 0){                
    $this->response($this->json(array( 'inserted_id' => mysqli_insert_id($this->db))), 200);
}

$error = array('status' => "Failed", "msg" => "Failed To Insert ".$string);
$this->response($this->json($error), 400);

更新

这样的调用完成没有错误,但在新创建的行上sortingId为0。它应该是从auto_increment

生成的id的Int
$sql = mysqli_query($this->db, $sql0.$sql1);
$sql = mysqli_query($this->db, $sql2);

if(mysqli_insert_id($this->db) > 0){                
    $this->response($this->json(array( 'inserted_id' => mysqli_insert_id($this->db))), 200);

}

1 个答案:

答案 0 :(得分:0)

你不能用mysqli_query做多查询,总是分开查询是个好主意。

如果你真的不能做其他事情,PHP中就有这个功能:

mysqli_multiquery(...)