erdomester February 2016

SQL query in php function 500 server error

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?

Answers


Diego Mariani February 2016

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

Post Status

Asked in February 2016
Viewed 3,526 times
Voted 13
Answered 1 times

Search




Leave an answer