-1

I've been creating a CMS blog using Bootstrap, PHP and MySQL and recently I figured out that the Edit Post functionality is not working. When I try to edit a post, it doesn't get updated on database, and I get the error: "Something went wrong. Try again."

Here is the file EditPost.php:

<?php
require_once("includes/DB.php");
require_once("includes/Functions.php");
require_once("includes/Sessions.php");

Confirm_Login();

$SearchQueryParameter = $_GET['id'];
if(isset($_POST["Submit"])){
  $PostTitle = $_POST["PostTitle"];
  $Category = $_POST["Category"];
  $Image = $_FILES["Image"]["name"];
  $Target = "uploads/".basename($_FILES["Image"]["name"]);
  $PostText = $_POST["PostDescription"];
  $Admin = "Mariam";
  date_default_timezone_set("America/Los_Angeles");
  $CurrentTime=time();
  $DateTime=strftime("%B-%d-%Y %H:%M:%S",$CurrentTime);

  if(empty($PostTitle)){
    $_SESSION["ErrorMessage"]= "The title must not be empty.";
    Redirect_to("Posts.php");
  }elseif (strlen($PostTitle)<=5) {
    $_SESSION["ErrorMessage"]= "The post title must be greater than 5 characters.";
    Redirect_to("Posts.php");
  }elseif (strlen($PostText)>10000) {
    $_SESSION["ErrorMessage"]= "The post description is limited to 10000 characters.";
    Redirect_to("Posts.php");
  }else{
    // Query to update the posts in DB when everything is fine
    global $ConnectingDB;
    if (!empty($_FILES["Image"]["name"])) {
      $sql = "UPDATE posts
              SET title='$PostTitle', category='$Category', image='$Image', post='$PostText'
              WHERE id='$SearchQueryParameter'";
    }else {
      $sql = "UPDATE posts
              SET title='$PostTitle', category='$Category', post='$PostText'
              WHERE id='$SearchQueryParameter'";
    }
    $Execute=$ConnectingDB->query($sql);
    move_uploaded_file($_FILES["Image"]["tmp_name"],$Target);
    //var_dump($Execute);
    if($Execute){
      $_SESSION["SuccessMessage"]="Post updated successfully!";
      Redirect_to("Posts.php");
    }else {
      $_SESSION["ErrorMessage"]= "Something went wrong. Try again.";
      Redirect_to("Posts.php");
    }
  }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
  <link rel="stylesheet" href="Css/Styles.css">
  <title>Edit Post</title>
</head>
<body>
  <!-- Navbar -->
  <div style="height:5px; background:red;"></div>
  <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
    <div class="container">
      <a href="Blog.php">
      <img src="img/logo.png" class="logo_brand">
      </a>
      <button class="navbar-toggler" data-toggle="collapse" data-target="#navbarcollapseCMS">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarcollapseCMS">
      <ul class="navbar-nav mr-auto">
        <li class="nav-item">
          <a href="MyProfile.php" class="nav-link"> <i class="fas fa-user text-success"></i> My Profile</a>
        </li>
        <li class="nav-item">
          <a href="Dashboard.php" class="nav-link">Dashboard</a>
        </li>
        <li class="nav-item">
          <a href="Posts.php" class="nav-link">Posts</a>
        </li>
        <li class="nav-item">
          <a href="Categories.php" class="nav-link">Categories</a>
        </li>
        <li class="nav-item">
          <a href="Admins.php" class="nav-link">Manage Admins</a>
        </li>
        <li class="nav-item">
          <a href="Comments.php" class="nav-link">Comments</a>
        </li>
        <li class="nav-item">
          <a href="Blog.php?page=1" class="nav-link" target="_blank">Live Blog</a>
        </li>
      </ul>
      <ul class="navbar-nav ml-auto">
        <li class="nav-item"><a href="Logout.php" class="nav-link text-danger">
          <i class="fas fa-user-times"></i> Logout</a></li>
      </ul>
      </div>
    </div>
    </nav>
    <div style="height:5px; background:red;"></div>
    <!-- Navbar end -->
    <!-- Header -->
    <!-- Header end -->
    <!-- Main area -->
    <section class="container py-1 mb-4">
      <div class="row">
        <div class="offset-lg-1 col-lg-10" style="min-height:400px;">
          <div class="user-messages">
            <div class="user-messages">
              <?php
              echo ErrorMessage();
              echo SuccessMessage();
              ?>
            </div>
            <?php
          // Fetching existing content
          global $ConnectingDB;
          $sql = "SELECT * FROM posts WHERE id='$SearchQueryParameter'";
          $stmt = $ConnectingDB ->query($sql);
          while ($DataRows=$stmt->fetch()) {
            $TitleToBeUpdated = $DataRows['title'];
            $CategoryToBeUpdated = $DataRows['category'];
            $ImageToBeUpdated = $DataRows['image'];
            $PostToBeUpdated = $DataRows['post'];
          }
           ?>
          <form class="" action="EditPost.php?id=<?php echo $SearchQueryParameter; ?>" method="post" enctype="multipart/form-data">
            <div class="card bg-secondary text-light mb-3">
              <div class="card-header">
                <h1 class="label-font-header"><i class="fas fa-edit" style="color:white;"></i> Edit Post</h1>
              </div>
              <div class="card-body bg-dark">
                <div class="form-group">
                  <label for="title"> <span class="FieldInfoWhite">Post Title: </span></label>
                  <input class="form-control" type="text" name="PostTitle" id="title" placeholder="Type the title here" value="<?php echo $TitleToBeUpdated; ?>">
                </div>
                <div class="form-group">
                  <span class="FieldInfoWhite">Existing Category: </span>
                  <?php echo $CategoryToBeUpdated; ?>
                  <br>
                  <label for="title"> <span class="FieldInfoWhite"> Choose Category: </span></label>
                  <select class="form-control" id="CategoryTitle" name="Category">
                    <?php
                    //Fetching all the categories from the category mysql_list_table
                    global $ConnectingDB;
                    $sql = "SELECT id,title FROM category";
                    $stmt = $ConnectingDB->query($sql);
                    while ($DataRows = $stmt->fetch()) {
                      $Id = $DataRows["id"];
                      $CategoryName = $DataRows["title"];
                    ?>
                    <option><?php echo $CategoryName; ?></option>
                  <?php } ?>
                  </select>
                </div>
                <div class="form-group mb-1">
                  <span class="FieldInfoWhite">Existing Image: </span>
                  <img class="mb-1" src="uploads/<?php echo $ImageToBeUpdated; ?>" width="150px"; height="90px";>
                  <label for="imageSelect"><span class="FieldInfoWhite"> Select Image </span></label>
                  <input type="File" name="Image" id="imageSelect" value="">
                </div>
                <div class="form-group">
                  <label for="Post"><span class="FieldInfoWhite">Post: </span></label>
                  <textarea class="form-control" id="Post" name="PostDescription" rows="8" cols="80">
                    <?php echo $PostToBeUpdated; ?>
                  </textarea>
                </div>
                <div class="row">
                  <div class="col-lg-6 mb-2">
                    <a href="Dashboard.php" class="btn btn-warning btn-block"><i class="fas fa-arrow-left"></i> Back to Dashboard </a>
                  </div>
                  <div class="col-lg-6" mb-2>
                    <button type="submit" name="Submit" class="btn btn-success btn-block"> <i class="fas fa-check"></i> Update </button>
                  </div>
                </div>
              </div>
            </div>
          </form>
        </div>
      </div>
    </section>
    <!-- Main area end -->
    <!-- Footer -->
    <div style="height:5px; background:red;"></div>
    <footer class="bg-dark text-white">
      <div class="container-fluid text-center text-md-left">
        <div class="row">
          <div class="col-md-6 mt-md-0 mt-3">
            <br>
            <p class="text-center"><a style="color: white; text-decoration: none; cursor: pointer;" target="_blank"><img src="img/logo.png" class="footer-img"></a><br>Everybody Fan Club is not endorsed by Madonna or her companies, nor does it seek to represent the official word on Madonna. We are expressly a fan-based site and any questions or concerns otherwise should be brought to Mariam's attention. Thank you very much!</p>
          </div>
          <hr class="clearfix w-100 d-md-none pb-3">
          <div class="col-md-3 mb-md-0 mb-3"></div>
          <div class="col-md-3 mb-md-0 mb-3">
            <br>
            <h5 class="follow-us">Follow Us:</h5>

            <ul class="list-unstyled">
              <li>
                <div class="col-mb-12">
                  <a href="https://www.facebook.com/Everybody-Fan-Club-584656684946852/" class="btn btn-primary social-media-btn">
                    <i class="fab fa-facebook-f pr-1"></i> Page
                  </a>
                </div>
              </li>
              <li>
                <div class="col-mb-12">
                  <a href="https://www.facebook.com/groups/everybodyfanclub/?ref=bookmarks" class="btn btn-primary social-media-btn">
                    <i class="fab fa-facebook-f pr-1"></i> Group
                  </a>
                </div>
              </li>
              <li>
                <div class="col-mb-12">
                  <a href="https://www.youtube.com/channel/UCvDESWkJZQmjIxai7SDHSnw" class="btn btn-danger social-media-btn">
                    <i class="fab fa-youtube pr-1"></i> Channel
                  </a>
                </div>
              </li>
              <li>
                <div class="col-mb-12">
                  <a href="" class="btn btn-light social-media-btn">
                    <i class="fab fa-instagram pr-1"></i> Instagram
                  </a>
                </div>
              </li>
            </ul>
          </div>
        </div>
      </div>
      <div style="height:60px; background:red;">
      <div class="footer-copyright text-center py-3">Copyright © <span id="year"></span> - Everybody Fan Club. All rights reserved
        <a href="" class="text-center"> Privacy policy</a>
      </div>
      </div>
    </footer>
    <!-- Footer end-->
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
<script>
  $('#year').text(new Date().getFullYear());
</script>
</body>
</html>

The posts table on MySQL database: enter image description here

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • You should print `$ConnectingDB->error` to see the reason why the query failed. – Barmar Feb 21 '20 at 22:46
  • You probably have SQL-injection problems, which would be solved by using prepared statements instead of substituting variables into the query. – Barmar Feb 21 '20 at 22:47
  • If `$PostText` contains an apostrophe you'll get a syntax error. Using parametrized statements will solve it. – Barmar Feb 21 '20 at 22:48
  • See this answer might help https://stackoverflow.com/a/59929664/12232340 –  Feb 21 '20 at 22:52
  • https://stackoverflow.com/a/22662582/285587 you need to configure error reporting for mysqli –  Feb 21 '20 at 22:59

1 Answers1

-1

I think your SQL statement is wrong at the end.

WHERE id='$SearchQueryParameter'

You are using id='$SearchQueryParameter' with ''. That is not necesarry for Int comparison.

Use WHERE id=$SearchQueryParameter instead.

davidev
  • 7,694
  • 5
  • 21
  • 56
  • That is right syntax in mysqli procedural queries, but not in prepared statement! And that is not only mistake going on in that query you pointed, look like it’s pdo statement and no execute, so it won’t return anything. Mainly all queries are full of the mistakes so, pointing mistakes one by one won’t help OP and OP needs to configure error reporting for mysqli –  Feb 21 '20 at 23:09
  • There isn't anything wrong with what they're using now. Even if the query/id column was an integer, MySQL will compensate for it. So what you posted as an answer, won't and will not help solve the question. – Funk Forty Niner Feb 22 '20 at 14:33