【问题标题】:SQL query in php function 500 server error [duplicate]php函数500服务器错误中的SQL查询[重复]
【发布时间】:2016-02-08 17:08:09
【问题描述】:

我遇到了一件很奇怪的事情。

这会引发 500 服务器错误:

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();

运行良好:

 $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"];

我只删除了第一行和最后两行。 有人对此有解释吗?

【问题讨论】:

  • 请告诉我们$conn 的定义位置
  • 是的,可能需要一个 - global $conn;
  • 只需在你的函数中添加global $conn;
  • 我很确定这是 $conn 的事情。我马上回来。

标签: php pdo


【解决方案1】:

您可能错过了$conn 变量范围

 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();

只需使用global $conn 从全局范围内检索$conn 变量。在http://php.net/manual/en/language.variables.scope.php查看更多global关键字

【讨论】:

  • 我不知道这个。谢谢!
猜你喜欢
  • 2016-08-05
  • 2016-11-28
  • 2016-06-18
  • 1970-01-01
  • 1970-01-01
  • 2017-06-03
  • 2016-02-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多