dreamone5156 2017-03-16 13:28
浏览 14

如何在.htaccess中将index.php重写为url

I am trying to create a RESTful web service and having problem with the url part. I this index.php?ID=2 that displays e.g

{
"name": "Raymond",
"Nation": "USA"
}

But I want to convert the 'index.php?ID=2' to e.g 'localhost/club/player/2/' and still have the same output.

{
 "name": "Raymond",
 "Nation": "USA"
} 

Also lets say I have only 3 rows in my database with ID 1, 2, 3. How do I adjust my code so that when someone used correct ID, Ok 200 message displays or if ID is outside the one in my database error 400 would display.

Here is my code:

$dbhost = '127.0.0.1'; //host connection
$dbuser = "root"; //root connet
$dbpass = ""; //password intialization
$db = 'adminlogin'; //Database specification
$conn = new mysqli($dbhost, $dbuser, $dbpass, $db);
if (!$conn) {
    die('Could not connect: ' . mysql_error());
}
$id = $_GET['ID'];
if ($id){
$id = mysqli_real_escape_string($conn, $id);
}  else {
    echo 'no ID';
}
$query = "SELECT Name, Position, Nationality, Market FROM staffdb WHERE ID ='" . $id . "'";
$result = mysqli_query($conn, $query);
if (!$result) {
    printf("Error: %s
", mysqli_error($conn));
    exit();
}
$temp = array();
if ($result) {
    while ($row = mysqli_fetch_object($result)) {
        $temp = $row;
    }
    header('Content-Type: application/json; charset=UTF-8');
    $json_string = json_encode($temp, JSON_PRETTY_PRINT);
    print $json_string;
} else {
    echo 'no array';
}

Thanks alot!

  • 写回答

1条回答 默认 最新

  • drslez4322 2017-03-16 13:52
    关注

    The Apache module mod_rewrite allows you to rewrite URL requests that come into your server and is based on a regular-expression parser.

    You need to put this into .htaccess file

    RewriteEngine On 
    RewriteRule ^/club/player/([0-9]+)/$ index.php?ID=$1 [L]
    

    I believe that localhost is host name. So you simply skip this from rewrite rule.

    You don't need to change anything in your code. Since you pass your variable as ID

    评论

报告相同问题?

悬赏问题

  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)