-1

The code below gives a page not working error (internal server error).

<?php
session_start();
include 'connection.php';

  if(!empty($_POST["amount"]) && !empty($_POST["name"])){
    $amount = $_POST["amount"];
    $name = $_POST["name"];
    $rental_id = $_SESSION["rental_id"];
            
    $select = "SELECT id FROM expenses WHERE rental_id = ? AND name = ?";
    $statement2 = $con -> prepare($select);
    $data2 = ["$name", $rental_id];
    $statement2 -> execute($data2);
    $rows = $statement2 -> rowCount();

    if($rows == 0 ){
      try{
          $sql = "INSERT INTO expenses (rental_id, name, amount) VALUES (?, ?, ?)";
          $data = ["$rental_id", "$name", "$amount"];
          $statement = $con -> prepare($sql);
          $statement -> execute($data);
      }
      catch(Exception $e){
        $e -> getMessage();
        error_log($e -> getMessage());
      }
    }
  }
?>

I tried commenting lines to troubleshoot which line exactly was giving the error. I realized that "execute()" is the one that gave that error. I have used the same code format in some other pages and it works, only this code gives an error. Below is my connection code:

<?php
try{
    $server_name = "localhost";
    $dbname = "rental";
    $username = "kevin";
    $password = "";

    $con = new PDO("mysql:host=$servername; dbname=$dbname", $username, $password);

    $con -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
    $e -> getMessage();
} 
  • When your page displays 500 error, you should either turn displaying errors on or (if on a live server) check the error log – Your Common Sense Aug 11 '23 at 08:23
  • 1
    Besides, you must remove every try-catch statement from the code. And you shouldn't quote variables. – Your Common Sense Aug 11 '23 at 08:25
  • I just realized that the column I'm referencing in the SQL statement as "rental_id" is actually "rentals_id" in the table. I have edited the table and it is now working, thanks all. – KevinKarish Aug 11 '23 at 08:34

0 Answers0