简体   繁体   中英

PDO insert into MySQL Database not working with another PDO query

(I have no idea whether the title is descriptive or not. I'm not sure where the problem is, so it's kind of difficult to come up with a good title.)

So here's the thing. I'd like to insert values (from an HTML form) into a MySQL database using PDO.

So far so good. I managed to get the $_POST['xyz'] values and successfully inserted them into the DB. But now I'd like to make sure that there's only one row with the same email address ($email) and same question id ($qid). I did that by checking to row count, as you can see in the code. Not sure if that's a good way to do it or not.

Now I can successfully NOT insert two rows with similar email addresses, but for some reason I cannot insert any rows with any other email address. Been trying to figure out what I am doing wrong, but can't. So here's the code. Hope you can see what I did there (because I can't).

try {
        $cnnxn = new PDO("mysql:host=$db_host;dbname=$db_name", $db_username, $db_password);
    } catch (PDOException $e2) {
        die("ERROR: " . $e2->getMessage());
    }

    $query2 = $cnnxn->prepare("SELECT count(*) as cnt FROM grdj_replies WHERE email = :email AND question_id = :qid");
    $query2->bindParam(':email', $email);
    $query2->bindParam(':qid', $qid);

    $isQueryOk = $query2->execute();

    if ($isQueryOk) {
      $count = $query2->fetchColumn();
      } else {
      trigger_error('Error executing statement.'); 
    }
    $query2->closeCursor();


      if ($count > 0){
          echo '<div class="tools-alert tools-alert-red"><p>Sähköpostiosoitteellasi <strong>'.$email.'</strong> löytyy jo tallennettu vastaus tähän tehtävään. Jos haluat muuttaa vastausta, seuraa sähköpostiosoitteeseesi lähetetyn viestin ohjeita.<p>';
          echo '<p>(<a href="#">Klikkaa tästä, jos haluat lähettää ohjeet uudestaan osoitteeseen '.$email.'</a>.)</p></div>';
      }

    else {

        $cnnxn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTIONS);
        $cnnxn->exec("SET NAMES utf8");
        $query = $cnnxn->prepare("INSERT INTO grdj_replies (question_id, last_name, first_name, email, question_number, answer, status, accesstoken) VALUES (:qid, :lastname, :firstname, :email, :questionnumber, :answer, :status, :accesstoken)");
        $query->bindParam(':qid', $qid);
        $query->bindParam(':lastname', $last_name);
        $query->bindParam(':firstname', $first_name);
        $query->bindParam(':email', $email);
        $query->bindParam(':questionnumber', $question_number);
        $query->bindParam(':answer', $answer);
        $query->bindParam(':status', $status);
        $query->bindParam(':accesstoken', $accesstoken);
        $query->execute();

        if ($query !== false)
                    {
                        print "<div class=\"tools-alert tools-alert-green\">Vastauksesi on tallennettu!</div>";
                    }
        $query->closeCursor();
        $cnnxn = null; 
    }

Firstly, you are using ->bindParam() where ->bindValue() would be adequate (perhaps, more appropriate).

You ask whether your input processing is a good way to do things: I can't see that code. Rather than using superglobals, use filter_input() / filter_input_array()

The problem you describe might not be in the PHP code: take a closer look at the database indexing. Have you uniquely indexed grdj_replies by qid (eg do you have a primary key on "qid" alone)? Are there any other inadequate indexes which are blocking you from inserting additional rows into the table, for the same qid? Perhaps you should uniquely index jointly by qid, email.

You apply error handling to the creation of the PDO object (database connection); in cases like these, I often find it helpful to apply error handling (try/catch, $error->getMessage()) to the execution of the SQL statement (this way, you get to see what the database is trying to tell you. Has it thrown an excuse/explanation for not running the query?)

I suggest you to use a MySQL unique index :

ALTER TABLE `grdj_replies`   
  ADD  UNIQUE INDEX `UNIQUE_IDX` (`email`, `question_id`);

Now MySQL will make sure there's no other row with the same email and question_id before inserting a new row, you don't have to check it "manually". In the case there is already the same data, the INSERT request would fail.

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