>我有一个基本表单,它加载 15 个下拉框,每个框中具有相同的主题。 这是一个投票页面,用户可以在其中投票选出他最喜欢的主题或最不喜欢的主题。 我遇到的问题是,当我告诉他们时,主题没有被加载。这是我的代码。
.PHP
<?php
$Vote = new Vote();
class Vote {
public function GetTopic() {
$Connect = new mysqli("127.0.0.1", "root", "", "Data");
$Query = 'SELECT * FROM Topics';
if($Gather = $Connect->query($Query))
{
while($Row = $Gather->fetch_assoc())
{
$Topic = $Row['Topic'];
echo '<option>'.$Topic.'</option>';
}
$Gather->free();
}
else
{
echo 'Error';
}
$Connect->close();
}
public function LoadTopic() {
for($I = 15; $I > 0; $I--)
{
echo '<select><option>'.$I.'</option>'.$this->GetTopic().'</select>';
}
}
}
?>
如果你像这样使用你的函数,你应该返回你的html数据而不是输出它:
public function GetTopic() {
$Connect = new mysqli("127.0.0.1", "root", "", "Data");
$Query = 'SELECT * FROM Topics';
if($Gather = $Connect->query($Query))
{
$html = "";
while($Row = $Gather->fetch_assoc())
{
$Topic = $Row['Topic'];
$html .= '<option>'.$Topic.'</option>';
}
$Gather->free();
return $html;
} else
{
//handle error
}
$Connect->close();
}
让我们尝试一些更适合类的东西:
<?php
class Vote
{
private $connect;
public $topics = array();
public function __construct()
{
$this->connect = new mysqli( '127.0.0.1', 'root', '', 'Data' );
if( $this->connect->connect_errno )
{
echo "Error:(" . $this->connect->connect_errno . "): " . $this->connect->connect_error . ".";
}
}
public function GetTopics()
{
$Query = 'SELECT * FROM Topics';
if( $Gather = $this->connect->query( $Query ) )
{
while( $Row = $Gather->fetch_assoc() )
{
$this->topics[] = $Row['Topic'];
}
$Gather->free();
}
else
{
echo 'Error';
}
}
public function LoadTopics()
{
if( $max = count($this->topics) > 0 )
{
$html = "<select>rn";
for( $i = 0; $i < $max; ++$i )
{
$html .= "<option value=" . $i . ">" . $this->topics[$i] . "</option>";
}
$html .= "</select>rn";
return $html;
}
else
{
return false;
}
}
public function __destruct()
{
$this->connect->close();
}
}
?>
__construct((/__destruct(( 方法实际上是为了建立您的连接。您还可以组合这两个函数,并让GetTopics()
方法(我强制更改了一些方法和属性名称(运行查询,格式化结果并返回$html
。
此外,我升级了您的for
函数,如果您决定稍后向主题添加另一个条目,它将随之扩展,而不是通过 15 个静态行进行计数。
您可以使用以下命令调用它:
<?php
$vote = new Vote();
echo $vote->GetTopics()->LoadTopics();
?>
我看到答案已经选定,不希望我的工作浪费掉;D
交替GetTopics()
功能,全部合二为一。
public function GetTopics()
{
$Query = 'SELECT * FROM Topics';
if( $Gather = $this->connect->query( $Query ) )
{
$html = "<select>rn";
$i = 0;
while( $Row = $Gather->fetch_assoc() )
{
$html .= "<option value=" . $i . ">" . $Row['Topic'] . "</option>";
++i;
}
$html .= "</select>rn";
$Gather->free();
return $html;
}
else
{
return "Error: No Results Returned";
}
}
现在它只是被调用:
<?php echo $vote->GetTopics(); ?>