gpt4 book ai didi

php - Mysql Select 查询 where 条件不能正常工作

转载 作者:行者123 更新时间:2023-11-29 23:30:31 24 4
gpt4 key购买 nike

我有两个表销售和收据,表结构如下。

销售表

id   total sale_type     cust_id

1 100 credit 10

2 200 payment 9

收据

id  net_mount   payment_type  cust_id

1 50 CDM 10

2 150 Hand Over 9

我的问题是当我在我得到的条件下给出 sale_type 时 匹配销售表中的数据以及收货表中的数据, 当给定 sale_type 时,我只想要 sale 表的匹配值。 payment_type 的情况相同。

代码

 <?php
$where='where 1';
$where2='where 1';
if($sale_type<>'')
{
$where.=" and sale.sale_type='$sale_type'";

}
if($deposited_type<>'')
{
$where2.=" and receipt.deposited_type='$deposited_type'";

}

if($cust_name<>'' || $cust_id<>'')
{
$where.=" and (sale.cust_id='$cust_name' or sale.cust_id='$cust_id')";
$where2.=" and (receipt.cust_id='$cust_name'
or receipt.cust_id='$cust_id')";
}

select total, net_amount from (select total, null as net_amount,
2 as sort_col from sale $where union
all select
null as total, net_amount, 1 as sort_col from receipt $where2)
as a order by sort_col desc
?>

有机构可以解决这些问题吗?

最佳答案

查询的 FROM 部分必须根据您需要的表的功能进行参数化。你必须做这样的事情:

<?php
$where='where 1';
$where2='where 1';
if ($sale_type<>'' && $deposited_type<>'') {
$where.=" and sale.sale_type='$sale_type'";
$where2.=" and receipt.deposited_type='$deposited_type'";
$tables = "sales INNER JOIN receipt ON sales.cust_id. = receipt.cust_id"
}
else if($sale_type<>'') {
$where.=" and sale.sale_type='$sale_type'";
$tables = "sales"
}
else if($deposited_type<>'') {
$where2.=" and receipt.deposited_type='$deposited_type'";
$tables = "receipt"
}

然后您可以使用以下命令构建查询:

SELECT ...
FROM $tables
WHERE conditions with $where and $where2

谨防具有 receipt.deposited_type='$deposited_type' 等条件的 SQL 注入(inject)

关于php - Mysql Select 查询 where 条件不能正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26624185/

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