0

I am trying to modify a query that I had inserted using an update query instead the update query added an additional row to the database as well as not allowing me to update a row. I am using a form and giving the variables values during runtime. The main thing I don't understand why is a duplicate entry even a problem, if you are trying to update an already existing record? Please stick to the question do not give a separate suggestion to this question, for example: "You shouldn't do this, or that". Stick to the question. There is a SQL Injection attack or the way I am using INSERT INTO is incorrect thank you for your time. [EDITED] I am not sure if it is the order at which I put the if statements themselves or I have the syntax for one or the other SQL QUERY wrong. Thank you very much for your time if possible.

<?php
   $NewCharacterIDErr = $NewCharacterNameErr = 
   $NewCharacterEyeColorErr = $NewCharacterHairColorErr = 
   $NewCharacterSkinColorErr =
   $NewCharacterGenderErr = "";
   $NewCharacterName = $NewCharacterEyeColor = $NewCharacterHairColor = 
   $NewCharacterSkinColor = $NewCharacterGender = "";
      $CharacterIDErr = $CharacterNameErr = $CharacterEyeColorErr = 
        $CharacterHairColorErr
      = $CharacterSkinColorErr = $CharacterGenderErr = "";
      $newID = $CharacterID = $CharacterName = $CharacterEyeColor = 
      $CharacterHairColor = $CharacterSkinColor = $CharacterGender = "";
       $newIDErr = "";
?>

Above are where the variables are. Below is where those variables are checked with their subsequent values.

 <?php
      if($_SERVER["REQUEST_METHOD"] == "POST")
      { 
             //THIS IS WHERE THE RECORD WILL BE CREATED!!!!
         if (empty($_POST["CharacterID"])) 
         {
              $CharacterIDErr = "Character's ID must be made.";
         } 
        else 
        {
             $CharacterID = test_input($_POST["CharacterID"]);
             if (!preg_match("/[0-9]/", $CharacterID)) 
              {
                    $CharacterIDErr = "Only Numbers.";
              }
        }
          if (empty($_POST["CharacterName"])) 
            {
                 $CharacterNameErr = "Character name required.";
            } 
           else 
           {
                $CharacterName = test_input($_POST["CharacterName"]);
                if (!preg_match("/[a-z,A-Z]/",$CharacterName)) 
                 {
                       $CharacterNameErr = "Only letters and white spaces 
                      allowed";
                 }       
           }
           if (empty($_POST["CharacterEyeColor"])) 
           {
                 $CharacterEyeColorErr = "You need to enter character's eye 
                 color.";
           } 
           else 
           {
                 $CharacterEyeColor = test_input($_POST["CharacterEyeColor"]);
                 if (!preg_match("/[A-Z,a-z]/",$CharacterEyeColor)) 
                 {
                       $CharacterEyeColorErr = "Only letters, and white 
                      spaces allowed.";
                 }
           }
             if (empty($_POST["CharacterHairColor"])) 
             {
                 $CharacterHairColorErr = "You cannot leave this blank!";
             } 
             else 
             {
                 $CharacterHairColor = test_input($_POST["CharacterHairColor"]);
                 if (!preg_match("/[A-Z,a-z]/", $CharacterHairColor))               
                 {
                       $CharacterHairColorErr = "Please enter letters.";
                 }
             }
             if (empty($_POST["CharacterGender"])) 
             {
                 $CharacterGenderErr = "Please enter your character's gender..";
             } 
              else 
             {
                  $CharacterGender = test_input($_POST["CharacterGender"]);
                  if (!preg_match("/[A-Z,a-z]/",$CharacterGender)) 
                  {
                     $CharacterGenderErr = "Only letters!";
                  }
             }
            if (empty($_POST["CharacterSkinColor"])) 
            {
              $CharacterSkinColorErr = "Please enter your character's skin 
               tone.";
            } 
            else 
            {
               $CharacterSkinColor = test_input($_POST["CharacterSkinColor"]);
               if (!preg_match("/[A-Z,a-z]/",$CharacterSkinColor)) 
               {
                   $CharacterSkinColorErr = "Only letters";
               }
            }
            //RECORD CREATION ENDS!!!
            //THIS IS THE BACKEND WHERE THE CHARACTER ID WILL BE MODIFIED!!!!
            if (empty($_POST["NewCharacterID"])) 
            {
                 $NewCharacterIDErr = "Character's ID must be made.";
            } 
           else 
           {
                $NewCharacterID = test_input($_POST["NewCharacterID"]);
                if (!preg_match("/[0-9]/", $NewCharacterID)) 
                 {
                       $NewCharacterIDErr = "Only Numbers.";
                 }
           }
             if (empty($_POST["NewCharacterName"])) 
               {
                    $NewCharacterNameErr = "Enter new character name";
               } 
              else 
              {
                   $NewCharacterName = test_input($_POST["NewCharacterName"]);
                   if (!preg_match("/[a-z,A-Z]/",$NewCharacterName)) 
                    {
                          $NewCharacterNameErr = "Only letters and white spaces 
                          allowed";
                    }             
              }
              if (empty($_POST["NewCharacterEyeColor"])) 
              {
                    $NewCharacterEyeColorErr = "Please enter characte
                    r's eye color.";
              } 
              else 
              {
                    $NewCharacterEyeColor = 
                   test_input($_POST["NewCharacterEyeColor"]);
                    if (!preg_match("/[A-Z,a-z]/",$NewCharacterEyeColor)) 
                    {
                          $NewCharacterEyeColorErr = "Only letters, numbers, and 
                         white spaces allowed.";
                    }
              }
                if (empty($_POST["NewCharacterHairColor"])) 
                {
                    $NewCharacterHairColorErr = "You cannot leave this blank!";
                } 
                else 
                {
                    $NewCharacterHairColor = 
                    test_input($_POST["NewCharacterHairColor"]);
                    if (!preg_match("/[A-Z,a-z]/", $NewCharacterHairColor))                 
                    {
                          $NewCharacterHairColorErr = "Please enter letters.";
                    }
                }
                if (empty($_POST["NewCharacterGender"])) 
                {
                    $NewCharacterGenderErr = "Please enter your character's 
                     gender.";
                } 
                 else 
                {
                     $NewCharacterGender = 
                     test_input($_POST["NewCharacterGender"]);
                     if (!preg_match("/[A-Z,a-z]/",$NewCharacterGender)) 
                     {
                        $NewCharacterGenderErr = "Only letters!";
                     }
                }
               if (empty($_POST["NewCharacterSkinColor"])) 
               {
                 $NewCharacterSkinColorErr = "Please enter your character's skin 
                 tone.";
               } 
               else 
               {
                  $NewCharacterSkinColor = 
                   test_input($_POST["NewCharacterSkinColor"]);
                   if (!preg_match("/[A-Z,a-z]/",$NewCharacterSkinColor)) 
                  {
                      $NewCharacterSkinColorErr = "Only letters";
                  }
               }
               if (empty($_POST["newID"])) 
               {
                  $newIDErr = "Please enter an Id to modify.";
               } 
               else 
               {
                  //This is the WHERE value for the UPDATE Query.
                  $newID = test_input($_POST["newID"]);
                  if (!preg_match("/[0-9]/",$newID)) 
                  {
                      $newIDErr = "Only numbers.";
                  }
               }
        }
               function test_input($data) 
              {
                $data = trim($data);
                $data = stripslashes($data);
                $data = htmlspecialchars($data);
                return $data;
              }
       ?>

Below is the front end form for the Insert Into SQL statements. Above is where the values that are inserted are being checked to see if they meet requirements.

       <div class ="characterCreation">
            <h3>Character Creation Form</h3>
            <p><span class="error">* required field</span></p>
            <form method="post" action="<?php echo 
            htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 
                  Please Enter your Character's ID: <input type="number" 
                 name="CharacterID" 
                  value="<?php echo $CharacterID;?>">
            <span class="error">* <?php echo $CharacterIDErr;?></span>
            <br><br>
            Please Enter your Character's Name: <input type="text" 
            name="CharacterName" 
                  value="<?php echo $CharacterName;?>">
            <span class="error">* <?php echo $CharacterNameErr;?></span>
            <br><br>
             Please Enter your Character's Eye Color: <input type="text" 
             name="CharacterEyeColor" 
                   value="<?php echo $CharacterEyeColor;?>">
            <span class="error">* <?php echo $CharacterEyeColorErr;?></span>
            <br><br>
            Please Enter your Characters's Hair Color: <input type="text" 
            name="CharacterHairColor" 
                  value="<?php echo $CharacterHairColor;?>">
            <span class="error">* <?php echo $CharacterHairColorErr;?></span>
            <br><br>
                  Please enter your Character's Gender: <input type="text" 
                  name="CharacterGender"
                   value="<?php echo $CharacterGender;?>">
            <span class="error">* <?php echo $CharacterGenderErr;?></span>
                  <br><br>
                  Please enter your Character's Skin Color: <input type="text" 
                  name="CharacterSkinColor"
                   value="<?php echo $CharacterSkinColor;?>">
            <span class="error">* <?php echo $CharacterSkinColorErr;?></span>
                  <br>
            <input type="submit" name="submit" value="Enter">
        </form>
      </div>

Below is where after the submit button is being pressed the insert into query is being called.

<?php 
                  $sqlInsert = "INSERT INTO charactercreationtable ( 
                  Character_ID, Character_Name, Character_EyeColor, 
                   Character_HairColor,
                 Character_Gender, Character_SkinColor) 
                 VALUES ('$CharacterID', '$CharacterName', '$CharacterEyeColor', 
                  '$CharacterHairColor', '$CharacterGender', 
                  '$CharacterSkinColor')";
                  mysqli_query($db, $sqlInsert) 
                  or echo("This query failed!");
                  $linebreak = "<br>";
          ?>

Above is where the INSERT INTO SQL Query is being called.

     <div class ="modifyForm">
            <h4>Modifying the form.</h4>
            <p><span class="error">* required field</span></p>
          <form method="post" action="<?php echo 
             htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 
            Please Enter your Character's New ID: <input type="int" 
           name="NewCharacterID" 
            value="<?php echo $NewCharacterID;?>">
          <span class="error">* <?php echo $NewCharacterIDErr;?></span>
          <br><br>
          Please Enter your Character's New Name: <input type="text" 
           name="NewCharacterName" 
            value="<?php echo $NewCharacterName;?>">
          <span class="error">* <?php echo $NewCharacterNameErr;?></span>
          <br><br>
            Please Enter your Character's New Eye Color: <input type="text" 
           name="NewCharacterEyeColor" 
            value="<?php echo $NewCharacterEyeColor;?>">
          <span class="error">* <?php echo $NewCharacterEyeColorErr;?></span>
          <br><br>
          Please Enter your Characters's New Hair Color: <input type="text" 
            name="NewCharacterHairColor" 
            value="<?php echo $NewCharacterHairColor;?>">
          <span class="error">* <?php echo $NewCharacterHairColorErr;?></span>
          <br><br>
            Please enter your Character's New Gender: <input type="text" 
            name="NewCharacterGender" 
            value="<?php echo $NewCharacterGender;?>">
          <span class="error">* <?php echo $NewCharacterGenderErr;?></span>
            <br><br>
            Please enter your Character's New Skin Color: 
            <input type="text" name="NewCharacterSkinColor" value="<?php echo 
           $NewCharacterSkinColor;?>">
          <span class="error">* <?php echo $NewCharacterSkinColorErr;?></span>
            <br><br>
            Please enter which ID you would like to affect: <input type="text" 
           name="newID" value="<?php echo $newID;?>">
          <span class="error">* <?php echo $newIDErr;?></span>
            <br>
        <input type="submit" name="submit" value="Enter">
      </div>

Above is where the frontend form for the UPDATE SQL query. Below is where the record is the UPDATE SQL query.

<?php              
     //Here I am updating the table using this php sql query.
      $sqlModify = 
       "UPDATE charactercreationtable SET Character_ID ='$NewCharacterID',
       Character_Name = '$NewCharacterName',
      Character_EyeColor = '$NewCharacterEyeColor',
        Character_HairColor = '$NewCharacterHairColor', 
          Character_Gender = '$NewCharacterGender',     
         Character_SkinColor = '$CharacterSkinColor' 
          //Here I am declaring which row to affect.;
        WHERE '$newID'"
         //Here I am ordering the query to execute.
           mysqli_query($db, $sqlModify) or echo("This query failed!");
    ?>

Here is what is happening within the database once I try to modify the information within.

Here is what is happening within the database once I try to modify the information within.

For some reason the a random number gets entered into the database. Once modifying the record takes place. The PRIMARY KEY is set as the Character_ID also. ^

TylerH
  • 20,799
  • 66
  • 75
  • 101
Doomed
  • 11
  • 7
  • 1
    Why shouldn't we suggest alternatives, if they would be better? – ADyson Feb 10 '21 at 18:57
  • Anyway... UPDATE queries never create new rows, ever. It just doesn't happen. Something else is happening, if you're seeing new rows. The code you've provided isn't the source of that problem. – ADyson Feb 10 '21 at 18:57
  • 1
    Also, if that's all your code then, regardless of the above, the update will never work because you're not using the values submitted from the form. You need to take a basic PHP + html forms tutorial, as you haven't grasped some of the fundamental concepts. Also, please study how to prevent SQL injection in PHP – ADyson Feb 10 '21 at 19:00
  • Also generally there is never a good reason to alter a primary key value once it's been created. The value should have no purpose or meaning other than to uniquely identify that row for the lifetime of the table. If you mess with the value then other code or data which relies on that identifier could potentially break or start to point to the wrong record. I think you need to study some basic database design principles as well. don't run before you can walk. There's more to making a successful application than just hopefully chucking out some code. Groundwork needs to be done first. – ADyson Feb 10 '21 at 19:04
  • I updated the question @ADyson now I am getting the values from the form using $_POST. INSERT INTO queries create new rows. – Doomed Feb 10 '21 at 19:26
  • `INSERT INTO queries create new rows`...that's correct. But UPDATE queries don't. So the code you've shown can't be creating new rows. That was my point. – ADyson Feb 10 '21 at 20:07
  • I updated again @ADyson. You are correct. – Doomed Feb 10 '21 at 20:29
  • The snippets are separate so it's harder to see how they all fit together. But it seems like maybe you are running the INSERT every time, regardless of which form is submitted. e.g. you should only run the UPDATE if `$_POST["NewCharacterID"]` is not empty, and the INSERT only if `$_POST["CharacterID"]` is not empty. – ADyson Feb 10 '21 at 20:46
  • 2
    It is a very bad idea to use `die(mysqli_error($conn));` in your code, because it could potentially leak sensitive information. See this post for more explanation: [mysqli or die, does it have to die?](https://stackoverflow.com/a/15320411/1839439) – Dharman Feb 10 '21 at 20:48
  • @ADyson That stopped the double inserts thank you! I wish I could upvote. – Doomed Feb 10 '21 at 21:04
  • @Dharman you are completely right. I am somewhat tired I completely forgot! – Doomed Feb 10 '21 at 21:17
  • @ADyson I just thought it would be more readable if the codes were in snippets, and separated so you wouldn't have to scroll too much. Also the code reads from top to bottom the separation is there just to prevent scrolling too much. – Doomed Feb 10 '21 at 21:20
  • @ADyson The duplicate key problem is still there though but the extra record is not. – Doomed Feb 10 '21 at 21:28
  • Duplicate key will be simply because you already have another record with the same ID. Really you should be using an auto_increment field rather than allowing the user to specify or change the ID. – ADyson Feb 10 '21 at 22:42

1 Answers1

0

It seems like you are running both the INSERT and UPDATE every time, regardless of which form is submitted.

i.e. you should only run the UPDATE if $_POST["NewCharacterID"] is not empty, and the INSERT only if $_POST["CharacterID"] is not empty.

Really though you should be using an auto_increment field rather than allowing the user to specify or change the ID.

ADyson
  • 57,178
  • 14
  • 51
  • 63
  • 1
    I did exactly as you said. I reset the auto_increment I put some empty functions and I removed the code that affected the Character_ID and just let auto_increment do it's thing. I guess there was a conflict between the auto incrementation and the modify function. Thank you very much! – Doomed Feb 11 '21 at 00:14