首页 > 解决方案 > 如果第一个查询在 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>";
?>

老实说,我不知道在哪里以及如何放置第二个查询,任何想法和指导我都会非常感激!

标签: phphtmlmysqlforms

解决方案


举例来说;我并不是说它很漂亮,但我希望这更多的是数据模型的弱点,而不是我的编码技能......

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 |
+--------+----+

推荐阅读