dtt2012 2017-08-13 16:31
浏览 14
已采纳

将PHP变量设置为MySQL通配符'%'[重复]

This question already has an answer here:

I'm trying to query posts using PDO where the database column 'tags' = something.

My problem is: I want my query to work even if there's no $_GET['tag'] request is set and here's my code.

if (!isset($_GET['tag'])) {
    $tags = '%';
} else {
    $tags = $_GET['tag'];
}

$get_recipes = $con->prepare ("SELECT * FROM recipes WHERE tags = ?");
$get_recipes->execute(array($tags));
$recipes = $get_recipes->fetchAll();

Is it valid to set the PHP variable $tags to the MySQL wildcard %? if not possible then what should I do to make my query work?

When I run that code and there's not $_GET['tag'] is written the query will not fetch any posts from the database.

</div>
  • 写回答

1条回答 默认 最新

  • douhun7609 2017-08-13 16:44
    关注

    Using Wildcards in Prepared Statements With PDO

    When using a wildcard in MySQL you must use the LIKE operator. It is correct to bind the wildcard with parameters in PDO.

    You would prepare your statement like so.

    $get_recipes = $con->prepare ("SELECT * FROM recipes WHERE tags LIKE ?");
    

    And then you would bind your parameter using the % character, like so.

     $get_recipes->execute(array('%'));
    

    While that is the correct way to use a wildcard in the way you've proposed, that is not the correct solution to do what you're trying to do.

    How to achieve what you're trying to achieve

    In your code it looks like you want to select all rows if $_POST['tags'] is not set, and if it is set you want to select all rows that have the tags column set to the value of $_POST['tags']. To do this, you would want to prepare your statement inside the conditional, like so.

    if (!isset($_GET['tag'])) {
        $get_recipes = $con->prepare ("SELECT * FROM recipes");
        $get_recipes->execute();
    } else {
        $get_recipes = $con->prepare ("SELECT * FROM recipes WHERE tags = ?");
        $get_recipes->execute(array($_GET['tag']));
    }
    
    $recipes = $get_recipes->fetchAll();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)