【问题标题】:Passing PHP arguments to function call not working将 PHP 参数传递给准备好的语句函数调用不起作用
【发布时间】:2014-11-16 02:55:22
【问题描述】:

我的脚本中有一个SELECTprepared 语句,它为每个结果回显以下标记:

'<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>');
?>

我似乎无法让上面的代码工作,我怀疑它与结果绑定有关?

理想情况下,我希望能够从不同的地方调用函数,并能够通过传递参数来指定我想要返回的结果。

这可能吗?

【问题讨论】:

  • echo '未找到结果';这部分会受到打击吗?

标签: php function mysqli prepared-statement


【解决方案1】:

$userid$name$country 未在函数范围内定义。

你可能会这样做:

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();
}

并将函数调用更改为:

getResults('<div class="checkboxwrapper"><input type="checkbox" name="checkbox[]" value="%s">%s</div>');

【讨论】:

  • 感谢乔希的解释。我想我会在这里做一些编辑。无法自拔。
【解决方案2】:

在 index.php 中调用 getResults() 时,$name 和 $userid 没有定义。

您必须使用一个模板或多个字符串。

将带有变量的字符串作为一个参数传递给函数是行不通的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-23
    • 2014-07-17
    • 2020-09-13
    • 2015-10-11
    • 1970-01-01
    • 1970-01-01
    • 2012-06-07
    • 2011-11-10
    相关资源
    最近更新 更多