我在脚本中准备了一个SELECT
语句,它为每个结果返回以下标记:
'<div class="checkboxwrapper"><input type="checkbox" name="checkbox[]" value="' . $userid . '">' . $name . '</div>'
在我的标记中包含所有这些额外的代码似乎有些庞大。
是否可以以某种方式将准备好的语句保存在一个单独的文件中,将其包含在脚本的顶部,然后简单地调用该函数,根据我想要的结果向其传递一个参数?
即:
getresult.php
<?php
function getResults($output) {
global $db;
$stmt = $db->prepare("SELECT UserID, Name, Country FROM Dummy");
$stmt->execute();
$stmt->store_result();
$rows = $stmt->num_rows();
$stmt->bind_result($userid, $name, $country);
if($rows) {
while($stmt->fetch()) {
echo $output;
}
} else {
echo 'No Results found';
}
$stmt->close();
}
indexp.php
<?php
getResults('<div class="checkboxwrapper"><input type="checkbox" name="checkbox[]" value="' . $userid . '">' . $name . '</div>');
?>
我似乎无法让上面的代码工作,我怀疑这与结果绑定有关?
理想情况下,我希望能够从不同的地方调用函数,并能够通过传递参数来指定我想要返回的结果。
这可能吗?
您可能会这样做:
function getResults($output) {
global $db;
$stmt = $db->prepare("SELECT UserID, Name, Country FROM Dummy");
$stmt->execute();
$stmt->store_result();
$rows = $stmt->num_rows();
$stmt->bind_result($userid, $name, $country);
if ($rows) {
while($stmt->fetch()) {
echo sprintf($output, $userid, $name);
}
} else {
echo 'No Results found';
}
$stmt->close();
}
并将函数调用更改为:
getResults('<div class="checkboxwrapper"><input type="checkbox" name="checkbox[]" value="%s">%s</div>');
函数只应返回稍后可用于输出的空值。
function getResults($db) {
$result = $db->query("SELECT UserID, Name, Country FROM Dummy");
return $result->fetch_all(MYSQLI_ASSOC);
}
然后像这个一样调用
$data = getResults($db)
然后像这样在HTML输出中的某个地方使用的$data
<?php foreach ($data as $row): ?>
<div class="checkboxwrapper">
<input type="checkbox" name="checkbox[]" value="<?= $row['userid'] ?>">
<?= $row['name'] ?>
</div>
<?php endforeach ?>