我正在使用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'";
}
但在某些情况下仍然有效。
答案 0 :(得分:1)
使用连接!将所有变量放入字符串中非常糟糕。
<?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 . ';';