Issue
I have a SELECT
prepared statement in my script which echoes the following markup for each result:
'<div class="checkboxwrapper"><input type="checkbox" name="checkbox[]" value="' . $userid . '">' . $name . '</div>'
Having all of this extra code in my mark-up seems somewhat bulky.
Is it possible to somehow save this prepared statement in a separate file, include it at the top of my script then simply call the function, passing it a single argument depending on what results I want echoed out?
I.e.:
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>');
?>
I can’t seem to get the above code to work, I suspect it has something to do with the results binding?
Ideally, I’d like to be able to call the function from different places and be able to specify what results I want back through passing an argument.
Is this possible?
Solution
You could probably do something like this:
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();
}
and change the function invocation to:
getResults('<div class="checkboxwrapper"><input type="checkbox" name="checkbox[]" value="%s">%s</div>');
Answered By – yivi
Answer Checked By – Clifford M. (BugsFixing Volunteer)