php - "Get"函数不起作用,因为不是所有的连字符都应该被替换

标签 php mysql pdo get str-replace

我使用 Get 函数在 url 中查找字段 model 但当模型包含空格和连字符时我遇到了问题。 示例:我在 url 中的模型是“this-f-example”,数据库中的模型是“this f-example”(因此没有第一个连字符)。

我编写了以下 php 代码,但这还不够。它只会在我的数据库中查找 this f examplethis-f-example,因此它不会返回任何内容,因为这些模型不存在。

我应该如何更改我的代码,以便它也能查找模型 this-f examplethis f-example

完整网址:http//:www.example.com/test.php?model=this-f-example

数据库对应模型:这个f-example

<?php
    $pdo = new PDO ('mysql:host.....');    
    $model1 = str_replace ('-', ' ', $_GET['model']);
    $model2 = $_GET['model'];

    $sql = "SELECT DISTINCT brand, model FROM `exampletable` WHERE model = :model1 OR model = :model2";

    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(":model1", $model1);
    $stmt->bindParam(":model2", $model2);
    $stmt->execute();

    if($result = $stmt->fetch(PDO::FETCH_ASSOC))
    {
      echo $result['brand']; 
      echo $result['model'];
    }
?>

最佳答案

如果您在 url 中发送的变量 model 必须是 this-f-example,您可以使用 preg_replace而不是 str_replace 来获取 url 中模型的 model1model2

试试这段代码:

$modelUrl= $_GET['model'];    
$model1 = preg_replace('/-/', ' ', $modelUrl, 1);//remove the first hyphen

$occ = preg_match_all('/-/', $modelUrl, $matches, PREG_OFFSET_CAPTURE);
if ($occ !== false && $occ > 1) {
    //remove the second hyphen
   $model2 = substr_replace($modelUrl, ' ', $matches[0][2][1], strlen('-'));
}

$params = array(":model1"=> $model1,
                ":model2"=> $model2);

$sql = "SELECT DISTINCT brand, model FROM `exampletable` WHERE model=:model1 OR model=:model2";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);

但如果您的问题只是变量中的空格,我认为更好的解决方案是使用 urlencode()将使用 + 对变量中的空间进行编码的函数:

echo urlencode('this f-example'); // output : this+f-example

当您使用 $GET['model'] 获取它时,只需使用 urldecode()解码变量并删除 + 的函数:

echo urldecode($GET['model']); // output : this f-example

关于php - "Get"函数不起作用,因为不是所有的连字符都应该被替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29656406/

相关文章:

php - 防止使用浏览器 url 直接访问图像

php - 如何检查数据库中的重复条目?

javascript - 图片从上传文件夹插入数据库

php - 检查pdo中mysql存储函数的 bool 返回值

php - 使用 PDO 准备语句插入多行

php - Mysql PDO 获取时的最大 LONGBLOB 数据长度

javascript - 发送请求时可以urlencode null吗?

php - 根据保存在数据库中的 IP 地址删除特定对象的投票访问权限

php - "my network"带有sql子查询的函数

php - 快速问题,IF 语句似乎不适用于禁用元素的 while 循环