php - 在 mysql 中搜索多个值

标签 php mysql

我正在使用 PHP 和 MySQL 创建一个搜索脚本。现在,我已经达到了这样的目的,但在某些情况下它的效果不是很好:

$id = JRequest::getInt('id');
$catid = JRequest::getVar('catid');     
$console = JRequest::getVar('console'); 
$ram = JRequest::getVar('ram');

if ($ram) {
    $ram = "AND rec_ram='$ram'";
}       

if ($console) {
    $console = "AND console='$console'";
}

$array = array(
    catid => $catid,    
    console => $console,
    ram => $ram,
);

$db = JFactory::getDBO();
$query = "SELECT * FROM #__content WHERE catid='$catid' $array[console] $array[ram]";

还有什么其他替代方法可以做到这一点?

有时值可能为空,这就是我使用的原因:

if ($console) {
    $console = "AND console='$console'";
}

但在某些情况下它仍然无法正常工作。

最佳答案

使用串联!将所有变量都放在一个字符串中是非常糟糕的。

<?php

    $conditions = '';

    if ($ram) {
        $conditions .= ' AND `rec_ram`="'.$ram.'"';
    }       

    if ($console) {
        $conditions .= ' AND `console`="'.$console.'"';
    }

    $query = 'SELECT * FROM `#__content` WHERE `catid`=' . $catid . $condition . ';';

?>

请注意,如果 console 或 rec_ram 的类型为 int,则不需要引用它的值。

<?php

    // column console is int 
    if ($console) {
        $conditions .= ' AND `console`='.$console;
    }

?>

好的,这是提供正确的sql结构的方法:

$conditions = array();

if ($ram) {
    $conditions[] = '`rec_ram`="'.$ram.'"';
}

if ($console) {
    $conditions[] = '`console`="'.$console.'"';
}

// some other conditions...

$condition = '';
if (sizeof($conditions) > 0)
    $condition = ' WHERE ' . implode(' AND ', $conditions);

$query = 'SELECT * FROM `#__content`' . $condition . ';';

关于php - 在 mysql 中搜索多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13658311/

相关文章:

javascript - 有什么办法可以让我们在上传前获得视频时长?

php - 如何使用 PHP 向某些用户授予访问权限

php - 在另一个表 PHP 中按列排序

mysql - ruby ,MySQL2 : check if the result is empty

php - 无法获得使用 UTF-8 的编码,即使使用 &lt;metadata> 标记?

php - 在js中推送数组看起来无法正常工作

mysql - 如何通过一个查询在同一个表中插入多行?

mysql - 更改名称中包含空格的表

java - Wix 嵌入式 mysql 与 spring boot DDL 查询错误对于具有嵌入式 id 的实体

php - 覆盖外连接失败的记录的默认值