0

In PHP, I am trying to use a catch block for the situation where a user tries to enter a duplicate stock symbol (primary key) into a database. I've tried a couple things and the most common error I keep getting is:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'F' for key 'PRIMARY'

instead of my desired catch output that would tell the user the symbol is a duplicate and go back and try again.

Here are some examples of code I tried:

    } catch (mysqli_sql_exception $ex){
        if ($ex == 1062 ) {
            "Duplicate symbol... stock symbol already exists"; 
        }
    }

other attempts:

    } catch (SQLException $ex){
        if ($ex->getCode() == 1062 ) {
            "Duplicate symbol... stock symbol already exists"; 
        }
    }

...

    } catch (PDOException $ex){
        if ($ex->getCode() == 1062 ) {
            "Duplicate symbol... stock symbol already exists"; 
        }
    }

This is all of my current code for adding a company and stock info into a database (this code doesn't give any output - no errors, or confirmations):

<?php
include('topNavigation.php');
echo "<br>";

$symbol = htmlspecialchars(filter_input(INPUT_POST, 'symbol'));
$company_name = htmlspecialchars(filter_input(INPUT_POST, 'company_name'));
$current_price = filter_input(INPUT_POST, 'current_price', FILTER_VALIDATE_FLOAT);

if ($symbol == '' || $company_name == '' || $current_price < 0.0) {
    echo "You must complete all fields with valid data, try again.";
} else {
    try {
        require('dataBasePage.php');

        $query = "insert into stock (`symbol`, `company_name`, `current_price`) values (:symbol, :company_name, :current_price)";
        $statement = $db->prepare($query);
        $statement->bindValue(':symbol', $symbol);
        $statement->bindValue(':company_name', $company_name);
        $statement->bindValue(':current_price', $current_price);
        
        $statement->execute();

        $statement->closeCursor();

        echo $symbol . ' for ' . $company_name.' added successfully<br>';
    } catch (PDOException $ex){
        if ($ex->getCode() == 1062 ) {
            "Duplicate symbol... stock symbol already exists"; 
        }
    } catch (PDOException $ex) {
        echo "Connection error: " . $ex->getMessage();
    }
}
?>
Barmar
  • 741,623
  • 53
  • 500
  • 612
Brian Ball
  • 71
  • 7

0 Answers0