user255038
user255038

Reputation: 5

Delete record and count rows to check for result

So Im trying to delete a record from a table using php and sql and check whether it has been deleted using a rowcount() function in an if statement.

Im having problems on both fronts...

<?php

        echo $_GET['id'];

        if (isset($_GET['id'])) {
            $trainingID = $_GET['id'];
        }
        else {
            die('There was a problem with the ID given.');
        }

      // include the connection file
      require_once('./includes/connection.inc.php');
      $conn = dbConnect();
      // prepare SQL statement
      $sql = 'DELETE FROM  `trainingCourses` WHERE  `trainingID` =  "$trainingID"';
      $stmt = $conn->prepare($sql);
      try {
          $stmt->execute();
          echo "deleted";
          echo $stmt->rowcount();
          //check number of rows affected by previous insert
          if ($stmt->rowCount() == 1) {
              $success = "$trainingID has been removed from the database.";
          }
      }
       catch(PDOException $e){
           echo $e;
           echo 'Sorry, there was a problem with the database.';
      }

    ?>

I currently get 3 things outputted from my echo's throughout my code, firstly i get T0001, which is the primary key of the record i want to delete from another page. Secondly i get "deleted" which is from an echo within my 'try' statement but the record doesn't actually delete from the database. This is backed up from the rowcount() function which outputs 0.

I can't seem to get this working and im sure it should be simple and is something i am just overlooking!

Will the try method default to the catch if the "if" statement in it fails? As im also unsure what should be output from a rowcount() when a row has been deleted?

Any help you could offer would be really helpful! Thanks!

Upvotes: 0

Views: 1099

Answers (1)

Chris
Chris

Reputation: 3445

echo'ing this line

$sql = 'DELETE FROM  `trainingCourses` WHERE  `trainingID` =  "$trainingID"';

will treat $trainingID as string and not variable.

$sql = "DELETE FROM  `trainingCourses` WHERE  `trainingID` =  '$trainingID'";

will do the work BUT its not safe (sql injections). You should use PDO to bind varaibles like this

$sth = $dbh->prepare("DELETE FROM  `trainingCourses` WHERE  `trainingID` =  :id");
$sth->bindParam(":id",$trainingID);
$sth->execute();

Upvotes: 1

Related Questions