1

I have an edit button that can be clicked which will allow a table cell to become editable. It accepts numeric inputs. You can see below however, that if the input does not meet any of the criteria in my sql statement in my update-index.php table, that there should be some sort of error or I should get a message in my console saying The row failed to insert/update.

So, for example, if I enter 1517 into the table cell, which is a value that should produce The row failed to insert/update message, it does NOT insert or update which is what I want, however it gives me this message in my logs: Row inserted/updated successfully.

How can I get this to give me the correct message of what happened in my logs so that I can correctly display a message to the user so they do not think it was successfully entered, when it actually wasn't?

JavaScript:

// ----- Edit Row -----

$(document).on("click", "#skuTable .edit", function () {
  var $this = $(this);
  var tds = $this.closest('tr').find('td').filter(function () {
    return $(this).find('.edit').length === 0;
  });
  if ($this.val() === 'Edit') {
    $this.val('Save');
   if($this.id !== '.major_cat') {
        tds.not('.major_cat').not('.minor_cat').not('.rep_code').not('.sku_desc').not('.sku_status').not('.create_date').not('.sku').not('.sku_group').prop('contenteditable', true);

   }
  } else {
    var isValid = true;
    var errors = '';
    $('#myDialogBox').empty();
    var elements = tds;
    if (tds.find('input').length > 0) {
      elements = tds.find('input');
    }
    var dict = {}; 
    elements.each(function (index, element) {
      var type = $(this).attr('class');
      var value = (element.tagName == 'INPUT') ? $(this).val() : $(this).text();
      console.log(type);
      // ----- Switch statement that provides validation for each table cell -----
      switch (type) {
          case "sku":
              dict["SKU"] = value;
          break;
          case "group_id":
            if (!$.isNumeric(value)) {
                isValid = false;
                errors += "Please enter a numeric Group ID\n";
            }
            if (isValid) {
                dict["Group_ID"] = value.trim();
                }
        break;
        /*case "sku_group":
              dict["SKU Group"] = value.trim();
          break;*/
      }
    })
    if (isValid) {
        console.log(dict);
      $this.val('Edit');
      tds.prop('contenteditable', false);
      if(confirm("Saving will insert or update the data. Do you wish to continue?") == true) {
      var request = $.ajax({
          type: "POST",
          url: "update-index.php",
          data: dict
        });

        request.done(function (response, textStatus, jqXHR){
          if(JSON.parse(response) == true){
            console.log("row inserted/updated");
            alert("Row inserted/updated successfully");
          } else {
            console.log("row failed to updated");
            alert("The row failed to insert/update");
            console.log(response);
            console.log(textStatus);
            console.log(jqXHR);
          }
        });


        // Callback handler that will be called on failure
        request.fail(function (jqXHR, textStatus, errorThrown){
            // Log the error to the console
            console.log(textStatus);
            console.log(jqXHR);
            console.error(
                "The following error occurred: "+
                textStatus, errorThrown
            );
        });
        // Callback handler that will be called regardless
        // if the request failed or succeeded
        request.always(function () {

        });
      } else {
          alert("The entry was not saved");
        } // ends if statement with confirmation box
    } else {
      alert(errors);
    }
  }
});

update-index.php

  $Group_ID = $_POST['Group_ID'];
  $SKU = $_POST['SKU'];

  $host="xxxxxxxxx"; 
  $dbName="xxxxxx"; 
  $dbUser="xxxxxxxxxxxxxx"; 
  $dbPass="xxxx";

  $pdo = new PDO("sqlsrv:server=".$host.";Database=".$dbName, $dbUser, $dbPass);

  $sql = "IF EXISTS (SELECT SKU FROM SKU_Group_Index WHERE SKU = ?)
          AND EXISTS (SELECT Group_ID FROM SKU_Group_Dim WHERE Group_ID = ?)
            BEGIN
                UPDATE SKU_Group_Index
                SET Group_ID = ?
                WHERE SKU = $SKU
            END
            ELSE
            BEGIN
                IF EXISTS (SELECT Group_ID FROM SKU_Group_Dim WHERE Group_ID = ?)
                BEGIN
                INSERT INTO SKU_Group_Index (SKU, Group_ID) VALUES (?, ?)
            END
            END";

  $stmt = $pdo->prepare($sql);  
  $result = $stmt->execute([$SKU, $Group_ID, $Group_ID, $Group_ID, $SKU, $Group_ID]);
  echo json_encode($result);


?>
0

1 Answer 1

1

The problem is that you are only showing the failed message when the sql has an exception. Just because the row is not inserted doesn't mean the statement was invalid.

Returns TRUE on success or FALSE on failure.

http://php.net/manual/en/pdostatement.execute.php

So your sql executes successfully and doesn't do anything so the result of your ajax call will be true.

If you wish to know if your statement actually modified any data, you could use the following:

echo json_encode($stmt->rowCount() > 0)
Sign up to request clarification or add additional context in comments.

3 Comments

Is there a way to put something at the end of my query so that it basically gives me a false result or some sort of popup box?
You should use the PDOStatement::rowCount. $stmt->rowCount()
How could that be used correctly in my code. Whatever I am trying isnt working

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.