-1

I have the following code to insert a new record in a database:

<?php

require('comune.php');
$nome = $_POST['nome'];
$username = $_POST['username'];
$segreto = $_POST['password'];
$password = md5($segreto);
$validity = $_POST['validity'];
$ruolo = $_POST['ruolo'];
$funzione = $_POST['funzione'];
list($giorno, $mese, $anno) = explode('/', $validity);
$validity = implode('-', array($anno, $mese, $giorno));

try {
    $sql = "INSERT into utenti "
            . "(nome,username,segreto,password,validity,ruolo,funzione) "
            . "VALUES ('$nome', '$username', '$segreto', '$password', '$validity', '$ruolo', '$funzione')";
    $s = $pdo->prepare($sql);
    $s->execute();
} catch (PDOException $e) {
    $message = "ko";
}
$message = "ok";
//echo $sql;
echo $message;
?>

The issue I am facing is that, even if the query returns an error, $message is "ok". What am I doing wrong??

Tzar
  • 1,761
  • 2
  • 14
  • 21
Lelio Faieta
  • 6,457
  • 7
  • 40
  • 74

1 Answers1

0

change your code to

$sql = "INSERT into utenti (nome,username,segreto,password,validity,ruolo,funzione) "
        . "VALUES (?,?,?,?,?,?,?)";
$s = $pdo->prepare($sql);
$s->execute([$nome, $username, $segreto, $password, $validity, $ruolo, $funzione]);
echo "ok";

you will have either ok or informative error message

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
  • it is better to keep the try catch block: in the catch loop I have added $message="ko"; echo $message; exit(); and everything is ok – Lelio Faieta Mar 24 '14 at 18:41
  • @LelioFaieta it is not better. there is no point in echoing ok and there is no point in exit(); there should be either HTTP redirect on success or 500 error on error – Your Common Sense Mar 24 '14 at 18:43
  • your ajax should recognize HTTP response code. if it's different from 200, then it's error. For some strange reason you imagine that only PDO can cause an error, while it can be ANY code. At the same time full error message have to be LOGGED, instead of echoing useless ko – Your Common Sense Mar 24 '14 at 18:53