0

I ran into a very strange thing.

This throws an 500 server error:

function writeMsg() {

 $id='0000000625';
 $translation = 'word';
 try {
   $stmt = $conn->prepare("UPDATE table SET HUN=? WHERE ID=?");
   $stmt->execute(array($translation,$id));
   $response["success"] = 1;
   } catch(PDOException $e) {
   echo 'ERROR: ' . $e->getMessage();
   $response["success"] = 0;
  }
  echo 'RESPONSE: '.$response["success"];

}
writeMsg();

This runs fine:

 $id='0000000625';
 $translation = 'word';
 try {
   $stmt = $conn->prepare("UPDATE table SET HUN=? WHERE ID=?");
   $stmt->execute(array($translation,$id));
   $response["success"] = 1;
   } catch(PDOException $e) {
   echo 'ERROR: ' . $e->getMessage();
   $response["success"] = 0;
  }
  echo 'RESPONSE: '.$response["success"];

I only removed the first and the last 2 lines. Does anyone has an explanation to this?

erdomester
  • 11,789
  • 32
  • 132
  • 234

1 Answers1

0

You've probably missed the $conn variable scope

 function writeMsg() {

     global $conn;

     $id = '0000000625';
     $translation = 'word';

     try {

         $stmt = $conn->prepare("UPDATE table SET HUN=? WHERE ID=?");
         $stmt->execute(array($translation, $id));
         $response["success"] = 1;

     } catch(\PDOException $e) {
         echo 'ERROR: ' . $e->getMessage();
         $response["success"] = 0;
     }

     echo 'RESPONSE: ' . $response["success"];

}

writeMsg();

Just use global $conn to retrieve the $conn variable from the global scope. Check more at http://php.net/manual/en/language.variables.scope.php for global keyword