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

标签 php mysql

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

销售表

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/

相关文章:

android - 我试图从 android 将数据插入 mysql 数据库

mysql - SQL 查询应该聚合每行而不是多行的数据

mysql - 选择存储在基于 VARCHAR 的 CSV 字段中的所有值的集合

php - 从空值创建默认对象 - 简单的 HTML DOM

javascript - Rapidmail 订阅表格在电子邮件订阅后重定向 - Mailchimp

php - 如何在从mysql检索到的图像上加水印

mysql - 我可以通过 group_by 分成几列吗

php - 如何使用 php 在 wordpress 帖子中获取 gravatar?

java - Solr 突出显示返回 id

mysql - 如何查找多列中最常见的值