我有一个代码来执行此查询并按预期工作:
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);
}
你不能用mysql_query做多查询,总是把查询分开是个好主意。
如果你真的不能做其他事情,PHP中有这个功能:
mysqli_multiquery(...)