PDO / MySQL:使用预准备语句插入 - 500(内部服务器错误)

时间:2018-01-14 19:02:12

标签: php mysql ajax pdo

我正在用PHP和MySQL编写一个简单的数据库应用程序。我使用ajax运行脚本服务器端。我使用PDO编写了一个数据库类。

我已经编写了各种PHP脚本来处理插入数据,他们都在使用我的课程" prepare()"和"执行()"方法

我写了一个单独的php脚本来创建表并删除表,还插入了示例数据,并删除了所有数据。这是为了帮助我回到一个已知的"我正在构建和调试数据库应用程序时的数据集。

我在html中创建了四个按钮,我正在异步调用一个php脚本,传递一个名为" script"的变量。使用GET。在我的脚本中,我有一个switch语句,它确定要运行的SQL命令。我不需要绑定任何变量。

当我单击按钮执行脚本时,如果情况允许,它可以正常工作。因此,例如,如果我单击以删除所有表,它将删除表。但是,如果我再次单击它(并且没有要删除的表),则javascript将返回500 - 内部服务器错误。我想返回一条错误消息,但无法解决我的脚本中的问题。

以下是我的课程方法:

public function prepare($query){
  // PDO prepare allows for binding of values, removes threat of SQL injection and improves query performance
  $this->statement = $this->connection->prepare($query);
}

public function bind($parameter, $value, $type = null){
  // PDO bindValue binds inputs to placeholders
  if(is_null($type)){
    switch(true){
      case is_int($value):
        $type = PDO::PARAM_INT;
        break;
      case is_bool($value):
        $type = PDO::PARAM_BOOL;
        break;
      case is_null($value):
        $type = PDO::PARAM_NULL;
        break;
      default:
        $type = PDO::PARAM_STR;
    }
  }
  $this->statement->bindValue($parameter, $value, $type);
}

public function execute(){
  // Executes the prepared statement
  return $this->statement->execute();
}

public function allresults(){
  // Returns all results
  $this->execute();
  return $this->statement->fetchAll(PDO::FETCH_ASSOC);
}

这是使用ajax调用php脚本的关键部分:

switch ($script) {
  case "create":
      global $create_tables;
      global $database;
      $database->prepare($create_tables);
      $result = $database->execute($create_tables);
      if($result){
        echo "Success";
      }
      else{
        echo "Failed";
      }
      break;

其中一个按钮:

<button type="button" class="btn btn-success" onclick="library('newsql.php?script=create')">Create Tables</button>

我的js:

function library(path) {


xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
          document.getElementById("main").innerHTML = this.responseText;
      }
  };
  xmlhttp.open("GET",path,true);
  xmlhttp.send();
};

我认为它与预准备语句的标准返回有关,但是它可能与执行没有绑定变量的预准备语句或重复预编译语句而不更改变量有关吗?

1 个答案:

答案 0 :(得分:0)

所以你有一个诊断正在发生的事情的问题。

  • 在你的JS函数中,你处理状态== 200但没有错误(如500)
  • 在浏览器中打开开发控制台(F12)并转到“网络”选项卡,然后单击按钮获取500错误,您将能够看到ajax调用的标题和响应选项卡(请求/响应标头和html / json /无论响应)这是你的PHP
  • 在PHP上出现500错误并且您在Response中看不到任何内容,那么您的PHP脚本不会回显任何内容,但您可能会在PHP或Apache的错误日志中看到一些内容。当出现错误500时,您必须学会在每次通话时监控这些。然后你会看到你为你的通话获得错误500的确切原因,而不是你期望在你的JS功能上的200(OK)......

希望有所帮助。