简体   繁体   English

如何简化 PHP PUT 和 POST 代码?

[英]How can I simplify PHP PUT and POST code?

Is there a way to simplify PHP code so you don't have to manually enter all variables for a PUT (or POST) request if the request involves all columns of a certain (mySQL) table?有没有办法简化 PHP 代码,这样如果请求涉及某个(mySQL)表的所有列,您就不必为 PUT(或 POST)请求手动输入所有变量? Something like first making a GET request for a specific table's variable names and then making a map function for the SET and bindParam part?比如首先对特定表的变量名称发出 GET 请求,然后为 SET 和 bindParam 部分发出 map function 之类的东西?

For example for the following code:例如对于以下代码:

 case "PUT":
      $user= json_decode(file_get_contents('php://input'));
      $sql = "UPDATE exampleTable SET name = :name, description =:description, edited_at = :edited_at WHERE id = :id";
      $stmt = $conn->prepare($sql);
      $edited_at = date('Y-m-d H:i:sa');
    
      $stmt->bindParam(":id", $user->id);
      $stmt->bindParam(":name", $user->name);
      $stmt->bindParam(":description", $user->description);
      $stmt->bindParam(":edited_at", $edited_at);
    
      if($stmt-> execute()){
         $response = ['status'=> 1, 'message' => 'Record updated successfully'];
      }else {
         $response = ['status'=> 0, 'message' => 'failed to update record'];
      }
      echo json_encode($response);
      break;
    

I've tried the below code that I found here to get the variable names, but it's not working (not entirely sure about the syntax), included the $conn part for completeness我已经尝试了我在此处找到的以下代码来获取变量名,但它不起作用(不完全确定语法),包括 $conn 部分以确保完整性

    $conn = new PDO('mysql:host=' .$this->server .';dbname=' . $this->dbname, $this->user, $this->pass);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $sql = "SELECT * FROM exampleTable WHERE 0=1";
            $stmt = $conn->prepare($sql);
            $stmt->execute();
            $variables = $stmt->fetch(PDO::FETCH_ASSOC);
            echo json_encode($variables);

It's just giving me 'false' instead of an array with variable names它只是给我 'false' 而不是带有变量名的数组

You can bind the values in the execute您可以在执行中绑定值

$result_set->execute(array(
    ':id' => value,
    ':name' => value,
    ':description' => value,
    ':edited_at' => value
));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM