douzhang3822 2018-05-02 18:20
浏览 52
已采纳

干查询,稍后在php中的if语句中添加where子句

I'm a fan of a dry code. I'm not sure is doable but I'm trying to save me from writing a double query.

Here's my example:

$link       = $_SERVER['PHP_SELF'];
$link_array = explode('/', $link);
$page       = end($link_array);

In the first part of my code, I'm parsing my link.

if (strpos($link, 'something') !== false) {

    $sql = $ee->db->query("SELECT * FROM `mytable` WHERE order_id = '$page'");
        foreach ($sql->result() as $row) {
            $tracking_code = $row->tracking_id;
            $carrier_name  = $row->carrier_name;
            echo "The real carrier name is: {$carrier_name} .<br>";
            echo "The real tracking code is: " . $tracking_code . ' .<br>';
} else {

    $sql = $ee->db->query("SELECT * FROM `mytable` WHERE order_hash = '$page'");
        foreach ($sql->result() as $row) {
            $tracking_code = $row->tracking_id;
            $carrier_name  = $row->carrier_name;
            echo "The real carrier name is: {$carrier_name} .<br>";
            echo "The real tracking code is: " . $tracking_code . ' .<br>';
}

Then I run two queries: depends on the link that I'm parsing I'm gonna retrieve two different set of data.

I was wondering if it is possible to have a different approach, something in this line:

$sql = $ee->db->query("SELECT * FROM `mytable`");

right after my variables and then, inside the if statement:

if (strpos($link, 'something') !== false) {
    $sql =. $ee->db->query("WHERE order_id = '$page'");
    #code
} else {
    $sql =. $ee->db->query("WHERE order_hash = '$page'");
    #code
}

Or any other way to avoid to rewrite my code could be fine. In this case I'm not gonna save a lot, I'm just trying to understand what it could be the best approach.

  • 写回答

3条回答 默认 最新

  • dqs13465424392 2018-05-02 18:49
    关注

    Overlooking the injected $page variable issue, you really only need to replace the column name it looks like:

    $sql = $ee->db->query("SELECT * FROM `mytable` WHERE order_".((strpos($link, 'something') !== false)? "id" : "hash")." = '$page'");
    
    foreach ($sql->result() as $row) {
        $tracking_code = $row->tracking_id;
        $carrier_name  = $row->carrier_name;
        echo "The real carrier name is: {$carrier_name} .<br>";
        echo "The real tracking code is: " . $tracking_code . ' .<br>';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?