gpt4 book ai didi

PHP & MySQL : How can i neglect empty variables from select

转载 作者:太空宇宙 更新时间:2023-11-03 10:26:18 26 4
gpt4 key购买 nike

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

<?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)可以为空

我想要什么:我想忽略空白字段

假设 $var1(关键字)为空,它将选择所有空字段,但我希望如果 $var1 为空,结果将类似于

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

如果 $var2 为空,结果如下

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

如果 $var1 和 $var2 为空,结果会是这样

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

等等

最佳答案

试试这个。


$vars = array(
'keywords' => '', // instead of var1
'author' => '', // instead of var2
'date' => '', // instead of var3
'forums' => '', // instead of var4
);

$where = array();
foreach ($vars as $varname => $varvalue) {
if (trim($varvalue) != '') $where[] = "`$varname` = '" . mysql_real_escape_string($varvalue) . "'";
}
$result = mysql_query("SELECT DISTINCT title, description FROM table WHERE " . join(" OR ", $where));

关于PHP & MySQL : How can i neglect empty variables from select,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5200121/

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