简体   繁体   English

使用PHP检查MySQL查询中哪个表的结果?

[英]Check which table has the result in MySQL query, using PHP?

I am using the following MySQL query to check several tables for any results where the date is within 30 days. 我正在使用以下MySQL查询来检查几张表中日期在30天内的任何结果。

What I want to do is be able to also check which table had the result, not just whether the MySQL query found a result in general. 我想做的是还可以检查哪个表有结果,而不仅仅是MySQL查询是否通常找到了结果。

One of my tables is supplier_bank_details, so if there is a record in this table with a date which is less than 30 days old then I am echoing out bank detail information, otherwise if it's my other table supplier_invoices then I want to echo out invoice information. 我的一个表是supplier_bank_details,所以如果在这个表小于30天,然后我呼应了银行详细信息的日期的记录,否则,如果它是我的其他表supplier_invoices那么我想呼应出发票信息。

Here's what I have so far but I am really new to MySQL and struggling a bit. 这是到目前为止的内容,但是我真的是MySQL的新手,有点挣扎。 Please could someone show me what I would need to do to get this to work. 请有人告诉我我需要做些什么才能使它工作。

<?php require_once 'config.php'; ?>

<?php
$tbl_name = 'supplier_bank_details';
$tbl_name2 = 'supplier_invoices;

$query = "select * from $tbl_name, $tbl_name2 WHERE date > NOW() - INTERVAL 30 DAY ORDER BY date DESC";

$result = mysql_query($query) or die( mysql_error() );
$row = mysql_fetch_assoc($result); 

if(mysql_num_rows($result) > 0) {

$datetime1 = new DateTime(); // Today's Date/Time
$datetime2 = new DateTime($row['date']);
$interval = $datetime1->diff($datetime2);


if(mysql_num_rows($tbl_name) > 0) {

$account_number = '****'.substr($row['account_number'], -4);

echo '<div class="contracts_area"><div class="table_header"></div>';
echo '<div class="request"><p>Bank Details Changed</p><p>'.$row['sort_code'].'</p><p>'.$account_number.'</p><p>about '.$interval->format('%d days ago').'</p></div>';
echo '</div>';

}else{

some invoice info here

}else{

echo '<div class="no_activity">No Recent Activity</div>';    
} 

}?>

Not too elegant, but you can add a constant field to your query, which refers to the table name: 不太优雅,但是您可以在查询中添加一个常量字段,该常量字段引用表名:

select *,"tab1" as tablename from tab1

A column, called tablename will appear, wit with value of "tab1" in each row. 将会出现一个名为tablename的列,每行的值为"tab1" It works only if there is least one record in the table. 仅当表中至少有一条记录时,它才有效。

Update : it's more useful, when you join different tables into a single result set. 更新 :将不同的表连接到单个结果集中时,此功能更为有用。

Use separate queries if the data from both tables doesn't need to be merged together. 如果两个表中的数据不需要合并在一起,请使用单独的查询。 Have one function to get supplier_bank_details over the last x days, another to get supplier_invoices over the last x days, and then you can handle any logic about what you want to show in PHP. 有一个函数可以在最近的x天内获取Supplier_bank_details,另一个函数可以在最近的x天内获取Supplier_invoices,然后您就可以处理要在PHP中显示的任何逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM