SQL插入到选择问题

时间:2015-03-17 01:03:27

标签: php mysql sql-server

所以我认为我已经接近搞清楚但我的查询不会将“待定”表中的项目添加到“项目”表中。请各位帮我解决这个问题。此外,如果我想要它删除后,我应该添加INSERT INTO SELECT查询下面的代码吗?感谢

action.php的:

$sql = "INSERT INTO items (photo,title,description, name) SELECT  (photo,title,description, name) FROM pending";
$stmt = $conn->prepare($sql); 
$stmt->execute();

将“待处理”中的项目带入项目后删除查询的示例:

$idToDelete = filter_var($_POST["recordToDelete"],FILTER_SANITIZE_NUMBER_INT); 

//try deleting record using the record ID we received from POST


$sql = "DELETE FROM pending WHERE id = :id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':id', $idToDelete, PDO::PARAM_INT);   
$stmt->execute();

2 个答案:

答案 0 :(得分:1)

我认为你这样做会让你自己接受错误。

考虑在您发布INSERT SELECT之后但在开始删除之前将新行添加到待处理队列时会发生什么。

我认为你需要在一个循环中以更加可控的方式执行此操作,以确保只删除从pending复制到items的内容。

$sql = "SELECT photo,title,description, name FROM pending";
$select_pending = $conn->prepare($sql); 
$select_pending->execute();

$sql = "INSERT INTO items (photo,title,description, name) 
               VALUES (:photo,:title,:description, :name)";
$insert_items = $conn->prepare($sql); 

$sql = "DELETE FROM pending WHERE id = :id";
$delete_pending = $conn->prepare($sql); 

// only if you are using INNODB databases.
//$conn->beginTransaction();

while( $row = $select_pending->fetch_object() ) {

    $insert_items->bindParam(':photo',       $row->photo, PDO::PARAM_STR);
    $insert_items->bindParam(':title',       $row->title, PDO::PARAM_STR);
    $insert_items->bindParam(':description', $row->description, PDO::PARAM_STR);
    $insert_items->bindParam(':name',        $row->name, PDO::PARAM_STR);
    $insert_items->execute();


    $delete_pending->bind_param(':id', $row->id, PDO::PARAM_INT);
    $delete_pending->execute();
}

// only if you are using INNODB databases.
//$conn->commit();

答案 1 :(得分:0)

$sql = "INSERT INTO items (photo,title,description, name) 
SELECT  photo,title,description, name FROM pending";

删除()声明中的SELECT