如何实现两个php-mysql查询并在两个表中显示



我想查询两个表,并在同一个html页面中显示每个表,我使用两个php块,每个块用于每个查询,当我在页面中只使用一个<?php...?>块时,它运行得很好,但当使用两个块时,我会得到一个HTTP ERROR 500。我的代码是:

<!DOCTYPE html>
...
<?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 TableRows extends RecursiveIteratorIterator {
function __construct($it) {
parent::__construct($it, self::LEAVES_ONLY);
}
function current() {
return "<td style='width: 30px; border-bottom: 1px solid #000000;  border-right: 1px solid #000000; text-align:center;'>" . parent::current(). "</td>";
}
function beginChildren() {
echo "<tr>";
}
function endChildren() {
echo "</tr>" . "n";
}
}
$servername = "";
$username = "";
$password = "";
$dbname = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT R1, R2, R3, R4, R5 FROM chispazo_numeros");
$stmt->execute();
// set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
echo $v;
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>
<h2></h2>
<?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>
<th>MEDIA</th>
<th>PRIMOS</th>
<th>REP</th>
</tr>";
class TableRows extends RecursiveIteratorIterator {
function __construct($it1) {
parent::__construct($it1, self::LEAVES_ONLY);
}
function current() {
return "<td style='width: 30px; border-bottom: 1px solid #000000;  border-right: 1px solid #000000; text-align:center;'>" . parent::current(). "</td>";
}
function beginChildren() {
echo "<tr>";
}
function endChildren() {
echo "</tr>" . "n";
}
}
$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, MEDIA, N_PRIMOS, REP FROM chispazo_libres ORDER BY RAND() LIMIT 1");
$stmt1->execute();
// set the resulting array to associative
$result1 = $stmt1->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt1->fetchAll())) as $k1=>$v1) {
echo $v1;
}
}
catch(PDOException $e1) {
echo "Error: " . $e1->getMessage();
}
$conn1 = null;
echo "</table>";
?>
...

我不知道重复连接是否是最佳实践,我尝试将两个php块只放在一个中,但不起作用。

任何建议都将不胜感激。

在同一个php文件中声明了两个TableRows类。为了避免这种情况,请进行以下更改。

  • 将第一个TableRows类重命名为class FirstTableRows extends ...
  • 将第二个TableRows类重命名为class SecondTableRows extends ...
  • 在第一个foreach循环中,将new TableRows(...)更改为new FirstTableRows(...)
  • 在第二个foreach循环中,将new TableRows(...)更改为new SecondTableRows(...)

最新更新