简体   繁体   中英

Combining two queries into a single query

I have two queries and I want to combine them into one so that it only returns one row in my database.

I have tried UNION but I keep getting an error. Can anyone please advise me on the code for it?

Below are my queries:

if(isset($_POST["response"]))
{
    $query = "INSERT INTO response(response) VALUES (:response)";
    $statement = $conn->prepare($query);
    $statement->execute(
    array(
    ':response' => $_POST["response"]
    )
        );
    $query = " INSERT INTO response (student_id)
SELECT studentid
FROM student
WHERE studentid = '".$_SESSION['studentid']."'";
 $statement = $conn->prepare($query);
    $statement->execute(

        );

UNION is used for combining multiple SELECT queries into a single result set. Check the mySQL (or any generic ANSI SQL) documentation.

Anyway, for no apparent reason you are making two INSERT queries when it looks like you're inserting into the same table and presumably want to insert everything into the same row in the same table. Right now you will make 2 rows instead of 1. You can insert more than one field as part of a single query.

I'm thinking:

if(isset($_POST["response"]))
{
    $query = "INSERT INTO response (student_id, response) SELECT studentid, :response FROM student WHERE studentid = :studentID";
    $statement = $conn->prepare($query);
    $statement->execute(
      array(
        ':response' => $_POST["response"],
        ':studentID' => $_SESSION['studentid']
      )
   );
}

However, since you only require the studentID in the table, and you already have the studentID from the session, it seems pointless to select from the students table at all. The only exception might be if you need to verify that the value in the session is correct - but surely you have already verified it before you added it to the session? If you haven't, you certainly should.

So in fact simply

if(isset($_POST["response"]))
{
    $query = "INSERT INTO response (student_id, response) VALUES (:studentID, :response)";
    $statement = $conn->prepare($query);
    $statement->execute(
      array(
        ':response' => $_POST["response"],
        ':studentID' => $_SESSION['studentid']
      )
   );
}

should be sufficient.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM