php - 如果第一个查询在 mysql 和 php 中为空,如何执行第二个查询?
问题描述
我有一个将值传递给执行查询并显示结果的 php 文件的 html 表单。
现在我希望如果在第一个查询中结果为空(0 行),则执行完全相同的查询,但在另一个表上并显示结果。
这是执行第一个查询的代码:
<?php
echo "<table style='border: solid 1px black;'>";
echo "<tr>
<th>R1</th>
<th>R2</th>
<th>R3</th>
<th>R4</th>
<th>R5</th>
</tr>";
class TableRows1 extends RecursiveIteratorIterator {
function __construct($it1) {
parent::__construct($it1, self::LEAVES_ONLY);
}
function current() {
return "<td style='width: 70px;'>" . parent::current(). "</td>";
}
function beginChildren() {
echo "<tr>";
}
function endChildren() {
echo "</tr>" . "\n";
}
}
if( isset($_POST['submit']) )
{
$feature = $_POST['R1'];
$feature2 = $_POST['R2'];
$feature3 = $_POST['R3'];
$feature4 = $_POST['R4'];
$feature5 = $_POST['R5'];
};
$feature = $_POST['R1'];
$feature2 = $_POST['R2'];
$feature3 = $_POST['R3'];
$feature4 = $_POST['R4'];
$feature5 = $_POST['R5'];
$values = [$feature, $feature2, $feature3, $feature4, $feature5];
$servername = "";
$username = "";
$password = "";
$dbname = "";
try {
$conn1 = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn1->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt1 = $conn1->prepare(
"SELECT
R1,
R2,
R3,
R4,
R5,
FROM table
WHERE
R1 = ?
AND
R2 = ?
AND
R3 = ?
AND
R4 = ?
AND
R5 = ?");
$stmt1->bindParam(1, $feature, PDO::PARAM_INT);
$stmt1->bindParam(2, $feature2, PDO::PARAM_INT);
$stmt1->bindParam(3, $feature3, PDO::PARAM_INT);
$stmt1->bindParam(4, $feature4, PDO::PARAM_INT);
$stmt1->bindParam(5, $feature5, PDO::PARAM_INT);
$stmt1->execute();
// set the resulting array to associative
$result1 = $stmt1->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows1(new RecursiveArrayIterator($stmt1->fetchAll())) as $k1=>$v1) {
echo $v1;
}
}
catch(PDOException $e1) {
echo "Error: " . $e1->getMessage();
}
$conn1 = null;
echo "</table>";
?>
老实说,我不知道在哪里以及如何放置第二个查询,任何想法和指导我都会非常感激!
解决方案
举例来说;我并不是说它很漂亮,但我希望这更多的是数据模型的弱点,而不是我的编码技能......
DROP TABLE IF EXISTS table_a;
DROP TABLE IF EXISTS table_b;
CREATE TABLE table_a(id SERIAL PRIMARY KEY);
CREATE TABLE table_b(id SERIAL PRIMARY KEY);
INSERT INTO table_b VALUES (NULL),(NULL),(NULL);
SELECT x.*
FROM
( SELECT 1 source, id FROM table_a
UNION
SELECT 2, id FROM table_b
) x
JOIN
( SELECT MIN(source) min_source
FROM
( SELECT 1 source, id FROM table_a
UNION
SELECT 2, id FROM table_b
) n
) y
ON y.min_source = x.source;
+--------+----+
| source | id |
+--------+----+
| 2 | 1 |
| 2 | 2 |
| 2 | 3 |
+--------+----+
推荐阅读
- python - BST的高度超出预期+1
- c# - Unity 错误:索引超出了数组的范围
- node.js - Flutter + socket.io 连接
- python-3.x - 安装应用程序 E 时出现 ubuntu 错误:dpkg 被中断,您必须手动运行 'sudo dpkg --configure -a' 来纠正问题
- java - Android EditText 圆形框输入
- ruby-on-rails-6 - 使用 rails 6 和 webpacker 在 selected-rails 插件中添加新值
- c# - 将身份角色声明 Pk 类型更改为 Guid
- python - voice_client 和 url 突然在 discord.py 机器人中不起作用
- php - 如何过滤数组中的数字并删除字符串并返回新字符串?
- javascript - 替换整个 html 页面,包括脚本