gpt4 book ai didi

php - 在 mysql 中搜索多个值

转载 作者:行者123 更新时间:2023-11-29 00:37:30 25 4
gpt4 key购买 nike

我正在使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com