PHP &MYSQL:如何忽略选择中的空变量 [英] PHP & MYSQL: How can i neglect empty variables from select

查看:23
本文介绍了PHP &MYSQL:如何忽略选择中的空变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有 4 个变量并且我想从数据库中选择 DISTINCT 值

if i have 4 variables and i want to select DISTINCT values form data base

<?php
$var1 = ""; //this variable can be blank
$var2 = ""; //this variable can be blank
$var3 = ""; //this variable can be blank
$var4 = ""; //this variable can be blank

$result = mysql_query("SELECT DISTINCT title,description FROM table WHERE **keywords ='$var1' OR author='$var2' OR date='$var3' OR forums='$var4'** ");

?>

注意:部分或全部变量($var1,$var2,$var3,$var4)可以为空

note: some or all variables ($var1,$var2,$var3,$var4) can be empty

我想要的:我想忽略空字段

what i want: i want to neglect empty fields

假设 $var1(关键字)为空,它将选择所有空文件,但我希望如果 $var1 为空,结果将是这样的

lets say that $var1 (keywords) is empty it will select all empty fileds, but i want if $var1 is empty the result will be like

$result = mysql_query("SELECT DISTINCT title,description FROM table WHERE author='$var2' OR date='$var3' OR forums='$var4' ");

如果 $var2 为空,结果会像

if $var2 is empty the result will be like

$result = mysql_query("SELECT DISTINCT title,description FROM table WHERE keywords ='$var1' OR date='$var3' OR forums='$var4' ");

如果 $var1 和 $var2 为空,结果将类似于

if $var1 and $var2 are empty the result will be like

$result = mysql_query("SELECT DISTINCT title,description FROM table WHERE date='$var3' OR forums='$var4' ");

等等

推荐答案

特别感谢每一位 experimentX .. 您的回答帮助我获得了正确的功能,我刚刚将 (isset) 替换为 (!空)..那么一切都会好起来的

Thanks alot every one specially experimentX .. Your answer helped me to get the right function i Just replaced (isset) with (!empty) .. Then every thing will be more than OK

$vars = array(
        (!empty($_GET["var1"]))? " keyword = '". $_GET["var1"] ."' ": null, 
        (!empty($_GET["var2"]))? " author  = '". $_GET["var2"] ."' ": null,
        (!empty($_GET["var3"]))? " date    = '". $_GET["var3"] ."' ": null,
        (!empty($_GET["var4"]))? " forums  = '". $_GET["var4"] ."' ": null
    );


function myfilterarray($var)
{
    return !empty($var)?$var: null;
}

$newvars = array_filter($vars, 'myfilterarray');

$where = join(" OR ", $newvars);

$sql = "SELECT DISTINCT title, description FROM table ".(($where)?"WHERE ".$where: null);

echo $sql;

如果有空变量,这个函数会被忽略

with this function if there is empty variable it will be neglected

再次感谢大家的宝贵建议

Thanks again every one for your helpful suggestion

这篇关于PHP &amp;MYSQL:如何忽略选择中的空变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆