Question

I'm doing registration in PHP and I am stuck on an unexpected catch, can you help me please?

if (isset($_POST['nick']) && isset($_POST['heslo']) && 
    isset($_POST['email']) && isset($_POST['datnar']))
{
  try
    {
        $email = ($_POST['email']);
        $datnar = ($_POST['datnar']);        
        $nick = ($_POST['nick']);
        $heslo = md5($_POST['heslo']);
        $db->query("INSERT INTO tblosoba(`nick`, `heslo`, `email`, `datnar`) VALUES ($nick, '$heslo', $email, $datnar)");
        echo "Registrace dokončena.";
    catch( PDOException $Exception ) {
        echo "Uživatel existuje";
    }
}
Was it helpful?

Solution

You need to close the try block.

{
    try
    {
        $email = ($_POST['email']);
        $datnar = ($_POST['datnar']);
        $nick = ($_POST['nick']);
        $heslo = md5($_POST['heslo']);
        $db->query("INSERT INTO tblosoba(`nick`, `heslo`, `email`, `datnar`) VALUES ($nick, '$heslo', $email, $datnar)");
        echo "Registrace dokončena.";
    } //<-------------------------------------------- Here
    catch(PDOException $Exception ) {
        echo "Uživatel existuje";
    }
}

Warning : Your code is vulnerable to SQL Injection. You need to filter the $_POST values before passing it to your query.

Use Prepared Statements (Parametrized Queries) to ward off SQL Injection attacks as you are already using PDO.

OTHER TIPS

Add a closing curly bracket (}) before the catch

Here is how to fix your code

if (isset($_POST['nick']) && isset($_POST['heslo']) && 
    isset($_POST['email']) && isset($_POST['datnar']))

{
    $sql = "INSERT INTO tblosoba(`nick`, `heslo`, `email`, `datnar`) VALUES (?,?,?,?)";
    $data = [$_POST['nick'],$_POST['heslo'],$_POST['email'],$_POST['datnar']];
    $db->prepare($sql)->execute($data);
    echo "Registrace dokončena.";
}

Note that you should not use try-catch here but should use prepared statement instead

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top