开发者

Inserting values with a select subquery AND an additional variable

I have a query that updates a boolean value for a given record, then inserts that record into another table (depending on the action performed) using a sele开发者_StackOverflowct subquery. The select subquery is working fine, but how can I add an additional variable on to the end of the query to be inserted ? The reason why I need to do this is because the select subquery doesn't contain this data, and this data will only be stored in one of the two tables that the original record gets "copied" to.

$id = $_POST['id'];
$action = $_POST['action'];
$reason = $_POST['reason'];
if($action == "approve") {
    $statement = $db->prepare("UPDATE waiting SET wait = :status WHERE id = :id");
    $statement->bindValue(':status', 0);
    $statement->bindParam(':id', $id);
    $statement->execute();

    $statement = $db->prepare("INSERT INTO approved (fname, lname, student_id, email, type) SELECT fname, lname, student_id, email, type FROM waiting WHERE id = :id");
    $statement->bindParam(':id', $id);
    $statement->execute();
    $lastId = $db->lastInsertId();

    $statement = $db->prepare("UPDATE approved SET reason = :reason WHERE id = $lastId");
    $statement->bindParam(':reason', $reason);
    $statement->execute();
}

Basically I want to combine the insert query that uses a select subquery and the update query that updates the reason into one query. Is this syntactically possible?

EDIT: I should be more clear and state that the reason being passed is a string entered by a user into a text field. It's not a column or any other data in a table.

Thanks


You can always select a constant, and the reason value is just that from the SQL viewpoint, so you can write the insert as:

INSERT INTO approved (fname, lname, student_id, email, type, reason) 
SELECT fname, lname, student_id, email, type, :reason 
FROM waiting WHERE id = :id

Just bind the params then and run the query, and that's it.


Bbasically you can add an arbitary value to your select by simply hard coding the value in the query. To make it eaier to read you can alias it to the columnanme with 'YOUR VALUE' as reason

INSERT INTO approved (fname, lname, student_id, email, type, reason) 
SELECT fname, lname, student_id, email, type, '$reason' as reason
FROM waiting WHERE id = :id

However, you cant parameterize table or column names so you need to manually quote and escape the value into the query.


If there is a limited number of "reasons", you could have a separate reasons table and join in your SELECT

INSERT INTO approved (fname, lname, student_id, email, type, reason) 
  SELECT w.fname, w.lname, w.student_id, w.email, w.type, r.reason
    FROM waiting w, reasons r 
    WHERE w.id = :id and r.id = :reasonsid
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜