调用它时函数外的函数的Php echo变量

时间:2013-12-31 00:02:47

标签: php

我有这个php函数,它从数据库表中查找行

if (!function_exists("ContactLookup")) {
    function ContactLookup($column, $clause, $value, $limit1=0, $limit2=1)
    {
        global $conn;
        $ContactLookup_Sql= "select * from contacts where $column $clause $value LIMIT $limit1, $limit2";
        $ContactLookup_Rs = mysql_query($ContactLookup_Sql,$conn);
        while ($ContactLookup_Result = mysql_fetch_array($ContactLookup_Rs)) {
            $foremame =$ContactLookup_Result["forename"];
            $surname = $ContactLookup_Result["surname"];
        }
    }
}

这只是回应结果,但如果我想将结果放入选择元素,我该如何做?

在while循环中,我会创建变量,然后在调用函数时回显变量吗?或者还有另一种解决方法吗?

像:

<?php ContactLookup("company_sequence", "=", $result["contact"],"0","10"); ?>
><select name="contactsequence" id="contactsequence">
    <option value=""><?php echo $forename; ?></option>
        </select

2 个答案:

答案 0 :(得分:1)

让你的函数返回一个数组

function ContactLookup ($column, $clause, $value, $limit1=0, $limit2=1) {
    global $conn;
    $ContactLookup_Sql= "select * from contacts where $column $clause $value LIMIT $limit1, $limit2";
    $ContactLookup_Rs = mysql_query($ContactLookup_Sql,$conn);

    $results = [];
    while($ContactLookup_Result = mysql_fetch_array($ContactLookup_Rs))
    {
        $results[] = [
           'forename'=> $ContactLookup_Result["forename"], 
           'surname'=> $ContactLookup_Result["surname"]
        ];
    }
    return $results;
}

然后你可以遍历它:

<?php
$names = ContactLookup("company_sequence", "=", $result["contact"],"0","10"); 
echo '<select name="contactsequence" id="contactsequence">';
foreach($names AS $name){
   echo '<option value="">'.$name['forename'].'</option>';
}
echo '</select>';

答案 1 :(得分:1)

更改函数以将结果作为变量返回,而不是回显它们。

function ContactLookup ($column, $clause, $value, $limit1=0, $limit2=1) {
    global $conn;
    $ContactLookup_Sql= "select * from contacts where $column $clause $value LIMIT $limit1, $limit2";
    $ContactLookup_Rs = mysql_query($ContactLookup_Sql,$conn);
    $results=array();
    while($ContactLookup_Result = mysql_fetch_array($ContactLookup_Rs))
    {
        $results[] = array('forename'=>$ContactLookup_Result["forename"],'surname'=>$ContactLookup_Result["surname"];
    }
    return $results;
}

然后在你的显示循环中,

<?php $contacts=ContactLookup("company_sequence", "=", $result["contact"],"0","10"); ?>
<select name="contactsequence" id="contactsequence">
    foreach($contacts as $k=>$contact){?> 
       <option value="<?php echo $k;?>"><?php echo $contact['forename']; ?></option>
        <?php 
        }
   </select>