gpt4 book ai didi

PHP 使用条件 if/elseif/else 创建 MySQL 查询

转载 作者:行者123 更新时间:2023-12-01 00:43:31 25 4
gpt4 key购买 nike

我是 PHP 和 MySQL 的新手,正在尝试使用 php 为 MySQL 创建查询,下面是代码的当前状态,它仍然是 WIP,但是 if/elseif 结构已经给出了根据数据而变化的所需输出输入,例如可以如下

"SELECT * FROM tuntikortti WHERE PVM BETWEEN '2014-09-11' AND '2014-09-27' AND Henkilo =
'Van' AND Tyonumero = '123456' AND Toiminto = '123';"

我已经确认查询行本身在 MySQL 中有效,但我需要以某种方式将其放入 MySQL_query($con, The query here).

那么我如何获得整个 if/elseif 查询行的 php 输出构建在变量或类似物中以供使用?

<?php
include("db_connect.php");

$pvm1 = $_POST['pvm1'];
$pvm2 = $_POST['pvm2'];
$henkilo = $_POST['henkilo'];
$tyonumero = $_POST['tyonumero'];
$toiminto = $_POST['toiminto'];

/* MySQL query line build, beginning */
ECHO "SELECT * FROM tuntikortti WHERE ";

/* PVM */
if(!empty($pvm1) && !empty($pvm2)){
echo "PVM BETWEEN '". $pvm1 ."' AND '". $pvm2 ."'";
} elseif(!empty($pvm1)) {
echo "PVM = '". $pvm1 ."'";
};

/* Henkilo */
if(!empty($henkilo) && !empty($pvm1)){
echo " AND Henkilo = '". $henkilo ."'";
} elseif(!empty($henkilo)) {
echo " Henkilo = '". $henkilo ."'";
};

/* Tyonumero */
if(!empty($tyonumero) && (!empty($pvm1) || !empty($henkilo))){
echo " AND Tyonumero = '". $tyonumero ."'";
} elseif(!empty($tyonumero)) {
echo " Tyonumero = '". $tyonumero ."'";
};

/* Toiminto */
if(!empty($toiminto) && (!empty($tyonumero) || !empty($pvm1) || !empty($henkilo))){
echo " AND Toiminto = '". $toiminto ."'";
} elseif(!empty($toiminto)) {
echo " Toiminto = '". $toiminto ."'";
};

echo ";";

$query = mysqli_query($sql,$con);

echo "<table border='1'>
<tr>
<th>TID</th>
<th>PVM</th>
<th>Henkilo</th>
<th>Työnumero</th>
<th>Toiminto</th>
<th>Tunnit</th>
<th>Selite</th>
</tr>";

while($row = mysqli_fetch_array($query)) {
echo "<tr>";
echo "<td>" . $row['TID'] . "</td>";
echo "<td>" . $row['PVM'] . "</td>";
echo "<td>" . $row['Henkilo'] . "</td>";
echo "<td>" . $row['Tyonumero'] . "</td>";
echo "<td>" . $row['Toiminto'] . "</td>";
echo "<td>" . $row['Tunnit'] . "</td>";
echo "<td class='selitetyyli'>" . $row['Selite'] . "</td>";
echo "</tr>";
}

echo "</table>";

include("db_close_connection.php");
?>

最佳答案

检查这个例子并尝试修改你的代码,

$sql = '';
$sql = "SELECT * FROM tablename WHERE ";
if(condition){
$sql.= "fieldname = 'value'";
} elseif(condition) {
$sql.= "fieldname = 'value'";
};

$sql.= ";";
$query = mysqli_query($con,$sql);

关于PHP 使用条件 if/elseif/else 创建 MySQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26016108/

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