donmqryh49993 2015-11-19 18:13
浏览 45
已采纳

mysql其中column =所有可能的值

Is there any way to do something like this? Give the $variable a default value to make mysql return all the rows?

SELECT * FROM table WHERE column = ?;

bind_param('i', $variable);

It's not as stupid as it sounds... I need to filter content based on user input, so If user does not fill the input/select the value will be ALL (or the correct answer). I wouldn't like to print php variables inside the prepare() or make the default variable all the possible values. What is the correct way to do this?

I'm actually doing this:

if ($stmt = $mysqli->prepare(' SELECT t1.id, t2.*
                               FROM ' . $table . ' t1
                               INNER JOIN property t2 ON t2.id = t1.id
                               WHERE t2.use = ?
                               ' . $city_cond
                                 . $zone_cond . '
                               LIMIT ?, ?'))

But I wouldn't like to print inside the prepare() so I ask if is there any way to do it with the bind_param() and declaring a default value.

  • 写回答

1条回答 默认 最新

  • donglu1913 2015-11-19 18:25
    关注

    I use something like this for similar problems:

    $sql = 'SELECT * FROM table WHERE cond1 = ?';
    $sqlparams = array('cond1');
    if (!empty($column) && $column != 'ALL') {
        $sql .= ' AND column = ?';
        $sqlparams[] = $column;
    }
    // add more conditions, ORDER BY, LIMIT etc.
    $stmt = $dbh->prepare($sql);
    $stmt->execute($sqlparams);
    

    Differences with mysqli (untested):

    -    $sqlparams[] = $column;
    +    $sqlparams[] = array('s', $column);
    ---
    -$stmt->execute($sqlparams);
    +foreach ($sqlparams as $sqlparam) {
    +    $stmt->bind_param($sqlparam[0], $sqlparam[1]);
    +}
    +$stmt->execute();
    

    Maybe this can be done with named parameters and always bind, needed or not.

    Another approach:

    $sql = 'SELECT * FROM table WHERE cond1 = ? AND (1 = ? OR column = ?)';
    $stmt = $dbh->prepare($sql);
    $stmt->bind_param('i', (empty($column) ? 1 : 0));
    $stmt->bind_param('s', $column);
    $stmt->execute();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据