简体   繁体   中英

Passing PHP arguments to prepared statement function call not working

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?

Ie:

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 cant 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?

When you call getResults() in the index.php, $name and $userid are not defined.

You have to either work with a template or several string.

Passing String with Variables as one parameter to a function wont work.

$userid , $name , and $country aren't defined in the function scope.

You could probably do something like this:

function getResults($output) {  
    global $db;
    $userid  = '';
    $name    = '';
    $country = '';

    $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, $country);
        }
    } 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>');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM