【问题标题】:Creating a REST API with MySQL and PHP formatted as a JSON response使用格式化为 JSON 响应的 MySQL 和 PHP 创建 REST API
【发布时间】:2015-05-05 17:13:39
【问题描述】:

我正在尝试在不使用任何框架的情况下从头开始创建一个公共 REST API,并且我已经创建了当用户在地址末尾输入“...? list=all" 但是,我想通过 ID 检索一行或检索最受欢迎的项目。我知道我可能不得不在查询字符串中更改它,但是我将如何创建检索它的地址的结尾?比如 ?ID=05 (从数据库中检索行 ID 5)或 TOP=15 (检索前 15 行)。如果有更好或更有效的方法来重写我的代码,请随时告诉我。

<?php
    // Check Connection
if(!($db = mysqli_connect($server, $user, $password, $database))) {
    die('SQL ERROR: Connection failed: '.mysqli_error($db));
    exit;
    }
return $db;
}

    //call the passed in function
if(function_exists($_GET['list'])) {
    $_GET['list']();
} 

    //methods
function all(){
    $db = getMysqlDB();
    $query = "SELECT * FROM books;";
    $books_sql = mysqli_query($db, $query);
    $books = array();
    while($book = mysqli_fetch_array($books_sql)) {
        $books[] = $book;
    }
    $books = json_encode($books);
    echo $_GET['jsoncallback'].$books;
 }
?>

【问题讨论】:

    标签: php json rest


    【解决方案1】:

    一个基于 PHP 的 REST API 的简单开始是:

    <?php
    
    // get the HTTP method, path and body of the request
    $method = $_SERVER['REQUEST_METHOD'];
    $request = explode('/', trim($_SERVER['PATH_INFO'],'/'));
    $input = json_decode(file_get_contents('php://input'),true);
    
    // connect to the mysql database
    $link = mysqli_connect('localhost', 'user', 'pass', 'dbname');
    mysqli_set_charset($link,'utf8');
    
    // retrieve the table and key from the path
    $table = preg_replace('/[^a-z0-9_]+/i','',array_shift($request));
    $key = array_shift($request)+0;
    
    // escape the columns and values from the input object
    $columns = preg_replace('/[^a-z0-9_]+/i','',array_keys($input));
    $values = array_map(function ($value) use ($link) {
      if ($value===null) return null;
      return mysqli_real_escape_string($link,(string)$value);
    },array_values($input));
    
    // build the SET part of the SQL command
    $set = '';
    for ($i=0;$i<count($columns);$i++) {
      $set.=($i>0?',':'').'`'.$columns[$i].'`=';
      $set.=($values[$i]===null?'NULL':'"'.$values[$i].'"');
    }
    
    // create SQL based on HTTP method
    switch ($method) {
      case 'GET':
        $sql = "select * from `$table`".($key?" WHERE id=$key":''); break;
      case 'PUT':
        $sql = "update `$table` set $set where id=$key"; break;
      case 'POST':
        $sql = "insert into `$table` set $set"; break;
      case 'DELETE':
        $sql = "delete `$table` where id=$key"; break;
    }
    
    // excecute SQL statement
    $result = mysqli_query($link,$sql);
    
    // die if SQL statement failed
    if (!$result) {
      http_response_code(404);
      die(mysqli_error());
    }
    
    // print results, insert id or affected row count
    if ($method == 'GET') {
      if (!$key) echo '[';
      for ($i=0;$i<mysqli_num_rows($result);$i++) {
        echo ($i>0?',':'').json_encode(mysqli_fetch_object($result));
      }
      if (!$key) echo ']';
    } elseif ($method == 'POST') {
      echo mysqli_insert_id($link);
    } else {
      echo mysqli_affected_rows($link);
    }
    
    // close mysql connection
    mysqli_close($link);
    

    source

    如需更完整的实施,请查看:

    https://github.com/mevdschee/php-crud-api

    披露:我是作者。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-04
      • 1970-01-01
      • 2019-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      相关资源
      最近更新 更多