我有 2 个 PHP 表单。一个显示事件列表,另一个显示每个特定事件的结果。在带有事件列表的页面上,我希望可以创建一个超链接来访问每个事件的结果。
例如,在"事件"页面上,我单击第 2 行的超链接,然后将我带到包含该特定事件结果的结果页面。
任何帮助将不胜感激,因为我对PHP非常非常陌生。如果需要任何额外的细节,请随时询问。
谢谢。
编辑:抱歉,我将向您展示到目前为止的事件表单的外观:
<?php
mysql_connect('localhost','root','');
mysql_select_db('clubresults') or die( "Unable to select database");
$sql = "SELECT *, DATE_FORMAT(EventDate, '%d/%m/%y') as newdate FROM Events";
$result = mysql_query ($sql);
?>
<table border = 1>
<tr>
<th>Event ID</th>
th>Event Name</th>
<th>Event Date</th>
<th>Location</th>
</tr>
<?php
while ($row = mysql_fetch_array($result))
{
echo "</td><td>" . $row['EventID'] . "</td><td>" . $row['EventName'] . "</td><td>" . $row['newdate'] . "</td><td>" . $row['Location'] . "</td><tr>";
}
echo "</table>";
mysql_close();
?>
您不需要两个脚本,只需要一个:
events.php?list
events.php?event=1234
在那里,您只需要检查以下内容:
$db = new Database(); # simplified
/* show event details if requested */
if (isset($_GET['event']) {
if ($event = $db->getEventByID($_GET['event'])) {
printf('<h2>Event: %s</h2>', htmlspecialchars($event->title));
# ...
}
}
/* show the list if requested (or show it always, whatever pleases you) */
if (isset($_GET['list']) {
echo '<table>';
foreach($db->getEventList() as $event) {
printf('<tr><td><a href="?event=%d">%s</a></td></tr>'
, $event->ID, htmlspecialchars($event->title));
}
echo '</table>';
}
编辑:正如我在更新的问题中看到的那样,您应该从那些oldskool mysql_*
函数切换到我在示例中概述的类样式,因为它使用起来要简单得多。下面是一个与您的代码示例相近的代码示例:
<?php
/**
* My First PDO Databaseclass
*/
class Database extends PDO
{
public function __construct()
{
$host = 'localhost';
$name = 'clubresults';
$user = 'root';
$pass = NULL;
parent::__construct("mysql:host=$host;dbname=$name", $user, $pass);
$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// $this->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
public function getEvents()
{
$sql = "SELECT *, DATE_FORMAT(EventDate, '%d/%m/%y') as newdate FROM Events";
return $this->query($sql, PDO::FETCH_OBJ );
}
public function getEventByID($id)
{
$sql = sprintf("SELECT * FROM Events WHERE EventID = %d;", $id);
return $this->query($sql)->fetchObject();
}
}
$db = new Database();
?>
<table border=1>
<tr>
<th>Event ID</th>
th>Event Name</th>
<th>Event Date</th>
<th>Location</th>
</tr>
<?php
foreach($db->getEvents() as $event)
{
echo "</td><td>" . $event->EventID . "</td><td>" . $event->EventName . "</td><td>" . $event->newdate . "</td><td>" . $event->Location . "</td><tr>";
}
?>
</table>