如何以在 php 中作为字符串回显的形式填充单选按钮?
Posted
技术标签:
【中文标题】如何以在 php 中作为字符串回显的形式填充单选按钮?【英文标题】:how to populate radiobuttons in a form that being echoed as a string in php? 【发布时间】:2017-05-04 06:43:11 【问题描述】:我有一个 php 脚本,它通过 ajax 从 jquery 接收数据,然后执行查询以从 mysql 检索数据。取回数据后,我想用这些数据填充表单中的一堆单选按钮。该表单被附加到变量$output
中,该变量将作为字符串发送回ajax。如何根据数据填充单选按钮?我尝试了以下方法,但它所做的只是用以下结果“检查”覆盖字符串。任何帮助表示赞赏。
<td class="answers"><input type="radio" name="quality_of_service" value="4" "%'.($result["quality_of_service"] === 3) ? 'checked':''.'%"></td>
我的 PHP
<?php
$output = '';
if(isset($_POST['id']))
$id = $_POST['id'][0];
/* print_r($id);*/
try
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//begin the transaction
$stmt = $conn->prepare("SELECT quality_of_service, self_improvement, personal_behavior, organization_rules_commitment, team_work, appearance, work_with_high_responsibility, loyalty_to_organization, punctuality_on_work, office_maintaining, areas_of_improvement, points_of_weakness, points_of_strength FROM appraisals_table WHERE Apr_Id = :id");
$stmt->bindValue(':id', $id, PDO::PARAM_INT);
$stmt->execute();
// set the resulting array to associative
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if (!empty($result))
$output .= '
<form id="reviewForm" action="" method="POST">
<div id="myRate">
How would you rank the employee in the following areas ?<span class="error">*</span><br>
<table class="myRateTable">
<tr id="table-header">
<th></th>
<th>Excellent<br><br>(4)</th>
<th>Above Average<br><br>(3)</th>
<th>Average<br><br>(2)</th>
<th>Poor<br><br>(1)</th>
</tr>
<tr>
<td class="questions">Quality of Service</td>
<td class="answers"><input type="radio" name="quality_of_service" value="4" "%'.($result["quality_of_service"] === 3) ? 'checked':''.'%"></td>
<td class="answers"><input type="radio" name="quality_of_service" value="3"></td>
<td class="answers"><input type="radio" name="quality_of_service" value="2"></td>
<td class="answers"><input type="radio" name="quality_of_service" value="1"></td>
</tr>
</table>
</div>
</form>
';
echo $output;
catch(PDOException $e)
echo "Error: " . $e->getMessage();
$conn = null;
?>
【问题讨论】:
为什么要使用 2 个百分号? 【参考方案1】:你为什么不能让它简单一点,
if($result["quality_of_service"] === 3)
<td class="answers">
<input type="radio" name="quality_of_service" value="4" checked>
</td>
else
<td class="answers">
<input type="radio" name="quality_of_service" value="4">
</td>
【讨论】:
我的整个表单将有 40 个 if & else 语句。另外如何在字符串中添加 if 语句,我敢肯定你不能。 否,如果 $result 中有 40 个结果,那么您需要逐个迭代结果,并且为每个结果创建一个 tr。那么,如果不是这样,怎么可能有 40 个呢?只需添加一个,循环必须执行其余逻辑 不,$result 只有 10 个结果,但我有 10 个单选按钮问题,每个问题有 4 个选项。 您可能有 100 个结果。没关系,因为您需要在每个上loop
,因此上述代码将在循环中添加一次。以上是关于如何以在 php 中作为字符串回显的形式填充单选按钮?的主要内容,如果未能解决你的问题,请参考以下文章