Issues with updating a database table on submit with an HTML form

I am trying to create a function where a user can edit a preexisting post. When the user is taken to edit.php, they are presented with a form that shows them the existing data associated with that post. They can then make changes to any of the fields (description, category, add additional images, etc.) and, upon hitting a submit button, the updated information will show on the post page.

My issue with this is actually getting it to update the information. The form will show up with the preexisting info, and I can make changes to any of the fields. However, when I press submit, I am taken to the list of posts, yet the changes I made have not been updated in the SQL table.

There arenā€™t any errors that are being returned upon hitting submit. Everything is running smoothly except for the fact things arenā€™t actually being updated in the database.

I have been looking on several different sites for help on the matter, and I have tried several variations of my UPDATE query thinking that maybe I am calling it incorrectly. This is the iteration I am currently working with after attempting several other examples I found:

$query = $db->query(
          "UPDATE post 
           SET title='$title', price='$price', description='$description', category='$category'
           WHERE post_id='$id'");

I am fairly new to PHP, so it is very possible that I am making simple syntax errors that I am not noticing. Or it could be some other portion of my code that I am not executing properly. If anyone could have a look at my code and help point me in the right direction, I would greatly appreciate it.

Also, I would like to add that yes, I know my code is vulnerable to injection. My only concern right now is getting this function to work. Any security measures I will deal with after getting this to work.

PHP

<?php

if(!isset($_GET['id'])){
  header('Location: modify.php');
  exit();
}else{
  $id = $_GET['id'];
}

include('../includes/db_connect.php');

if(!is_numeric($id)){
  header('Location: inventory.php');
}

if(isset($_POST['submit'])){

  $title = $_POST['title'];
  $price = $_POST['price']; 
  $description = $_POST['description'];
  $category = $_POST['category'];
  $title = $db->real_escape_string($title);
  $price = $db->real_escape_string($price);
  $description = $db->real_escape_string($description);

  if($title && $price && $description && $category){
    $query = $db->query(
      "UPDATE post SET 
        title='$title', price='$price', description='$description', category='$category'
        WHERE post_id='$id'");
    if($query){
      echo "product updated";
    }else{
      echo "error";
    }
  }else{
    echo "missing data";
  }

    $postid = $db->insert_id;

  for($i=0; $i<count($_FILES["images"]["name"]); $i++)
  {
   $filetmp = $_FILES["images"]["tmp_name"][$i];
   $filename = $_FILES["images"]["name"][$i];
   $filetype = $_FILES["images"]["type"][$i];
   $filepath = "images/".$filename;

   move_uploaded_file($filetmp, $filepath);

   $sql = "INSERT INTO images (img_name, img_path, img_type, post_id) VALUES 
   ('$filename', '$filepath', '$filetype', '$postid')";
   $result = mysqli_query($db, $sql);
  }
 }        


?>

The HTML form This is the only portion of the HTML that pertains to this function.

        <form action="<?php echo $_SERVER['PHP_SELF']?>" method="POST" enctype="multipart/form-data">
              <?php

              $editsql = "SELECT * FROM post INNER JOIN categories ON categories.category_id=post.category_id WHERE post_id=' ".$id." '";
              $editquery = $db->query($editsql);
              if($editquery->num_rows !=1){
                header('Location: inventory.php');
                exit();
              }

              $editrow = $editquery->fetch_object();

              echo "<div class='form-group'>";
                  echo "<label>Title*</label>";
                  echo "<input type='text' name='title' class='form-control' value='".$editrow->title."' required>";
              echo "</div>";
              echo "<div class='form-group'>";
                  echo "<label>Price*</label>";
                  echo "<input type='text' name='price' class='form-control' value='".$editrow->price."'required>";
              echo "</div>";
              echo "<div class='form-group'>";
                  echo "<label>Category</label>";
                  echo "<select name='category' class='form-control'>";
                                echo "<option value='".$editrow->category_id."'>".$editrow->category."</option>";
                                $catquery = $db->query("SELECT * FROM categories");
                                while($row = $catquery->fetch_object()){
                                  echo "<option value='".$row->category_id."'>".$row->category."</option>";
                                }             
                   echo "</select>";
              echo "</div>";

              echo "<div class='form-group'>";
                  echo "<label>Description*</label>";
                  echo "<textarea type='textarea' name='description' class='form-control' required>".$editrow->description."</textarea>";
              echo "</div>";
              echo "<div class='form-group'>";
                  echo "<label>Image(s)</label>";
                  echo "<input type='hidden' name='size' value='1000000'>";
                  echo "<input multiple='multiple' name='images[]' type='file'/>";
              echo "</div>";
              echo "<div class='required'>";
                  echo "* indicates a required field";
              echo "</div>";
              echo "<button type='submit' name='submit' value='submit' class='btn btn-default'>EDIT POST</button>"
              ?>
        </form>
1 Like

When you use single quotes around a variable, the variable will not be evaluated. So in this database query, WHERE post_id='$id' there is no way for the query to pick up the value of $id. So that record will not be updated.

Try rewriting the query, and if you run into problems, let us know.

1 Like

I rewrote the query without the single quotes and I am still not having any luck with getting the record to update. Any other suggestions?

This is very insecure, but use single quotes around the entire query, so you can use double quotes around each variable. Within double quotes the variables will be evaluated. But you really are better off being concerned about writing the query the right way to avoid SQL injection from the start. Thereā€™s no point learning how to do things the insecure way, and then fixing them later.

3 Likes

I tried that, and I am still having issues with things not updating. Also, I do understand what you mean about that, so Iā€™ve gone ahead and used a prepared statement for this. Here is what Iā€™m currently working with:

if($title && $price && $description && $category){
$editquery = ā€œUPDATE post SET title=$title, price=$price, description=$description, category=$category WHERE post_id=$idā€;
$edquery = $db->prepare($editquery);
$edquery->bind_result(ā€œssssā€, $title, $price, $description, $category);
$edquery->execute();
if($edquery){
echo ā€œUpdated!ā€;
}else{
echo ā€œerrorā€;
}
}else{
echo ā€œmissing dataā€;
}

Could my issue also be because Iā€™m using a &_POST and $_GET simultaneously?

Since I have $_GET here:

if(!isset($_GET[ā€˜idā€™])){
header(ā€˜Location: delete.phpā€™);
exit();
}else{
$id = $_GET[ā€˜idā€™];
}

And $_POST in this portion here:

if(isset($_POST[ā€˜submitā€™])){

$title = $_POST[ā€˜titleā€™];
$price = $_POST[ā€˜priceā€™];
$description = $_POST[ā€˜descriptionā€™];
$category = $_POST[ā€˜categoryā€™];

I would say ā€œyesā€, because on your form submit, you donā€™t actually send any values through in $_GET as far as I can see - a simple var_dump of both arrays will confirm that - what values are shown when you debug that part of the code?

If you were sending the id in $_GET, Iā€™d expect the form action to be something like

<form action="<?php echo $_SERVER['PHP_SELF'] . "&id=" . $id;?>" method="POST" enctype="multipart/form-data">

So you either need to add that into the action parameter, or send $id through as a hidden form variable as you do with size.

It doesnā€™t explain why the code doesnā€™t simply go straight to modify.php, though, if thatā€™s the case, unless itā€™s trying but you have browser output before your header redirect, as you seem to in the form-drawing code.

1 Like

I tried adding that to the action parameter and nothing happened. However, when I run var_dump on edquery, it returns bool(false). At least it is now echoing ā€œerrorā€ from my code when it wasnā€™t before.

I also ran var_dump on $_GET and itā€™s returning the id of the page on submit. And I ran it on editquery and on submit, it shows the information I updated string(92) "UPDATE post SET title=okay, price=5,000.00, description=testestestest1, category=4 WHERE id=48" but the database is not being updated.

Then,if I remove the . "&id=" . $id form action and use a hidden variable instead, the code is now taking me to modify.php without updating on submit.

echo "<input type='hidden' name='id' value='".$id."'>";
echo "<input type='submit' name='submit' value='EDIT POST' class='btn btn-default'>";

Do you think the comma in ā€œ5,000.00ā€ might be getting seen as a delimiter and the 000.00 as a stray field name?

2 Likes

You need to learn to separate the business and display logic. The code you provided is very poorly done. It might work but it is wrong.

You would need to also change your code to reflect that the id field is now being delivered as part of the $_POST array instead of the $_GET array, did you do that?

1 Like

I forgot to add the id field into post, but once you pointed out I had overlooked it, I got it to work with some more tinkering to my code. Thank you!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.