【问题标题】:PHP: how to read values from functions that return arrayPHP:如何从返回数组的函数中读取值
【发布时间】:2012-08-30 08:33:41
【问题描述】:

所以我有表格:

    <form method="post">
    Name: <input type="text" name="name" value<? if(isset($_GET['edit'])) {echo '="'. person($_GET['edit']) .'"';} ?>/><br>
    Surname: <input type="text" name="surname" value<? if(isset($_GET['edit'])) {echo '="'. person($_GET['edit']) .'"';} ?>/><br>       
    Age: <input type="text" name="age" value<? if(isset($_GET['edit'])) {echo '="'. person($_GET['edit']) .'"';} ?>/><br>
    <input type="submit" value="Submit" name="submit"/> 
</form>

    function person($id) {
    $query = 'SELECT name, sname, age FROM persons WHERE ID='.$id.';';
    $result = mysql_query($query);
    return $row = mysql_fetch_row($result);
}

所以函数返回一个数组,我怎样才能从这个函数中得到只显示我:'name' / 'sname' / 'age' in each input value

【问题讨论】:

  • 使用 foreach 遍历数组并检查键是否匹配打印值否则不匹配,您可以在此处使用 in_array。你被困在某个地方了吗?

标签: php arrays function get


【解决方案1】:

首先使用mysql_fetch_assoc 用于使用字母键。

然后你可以在最新版本的 PHP 中这样做:

person($id)['name']

或者在旧版本的 PHP 中定义单独的数组:

$personData = person($id);
$name = $personData['name'];

【讨论】:

  • 我也是。+1 为你的答案。在这种美丽的答案中,我怎么能保持沉默
【解决方案2】:

它就像一个普通的数组,所以你可以使用[id]。如果您使用 mysql_fetch_row 它必须是从 0 到 n-1 的数字,其中 n 是数组中的项目数,以便您在查询中执行。如果你有 mysql_fetch_assoc,你可以使用 $test['name'], $test['sname'], $test['age']。

$test = person(5);

echo $test[0].$test[1].$test[2]; //will show name|sname|age (withouth '|').

【讨论】:

    【解决方案3】:
    $per=person('12');
    

    获取姓名姓名、姓名、年龄

    $per[0] for name, $per[1] for sname and $per[2] for age;
    

    【讨论】:

      【解决方案4】:
      $data = person($id);
      $name = $data['name'];
      

      但是你应该在你的 sql 语句中使用你的参数之前转义它们! 至少做一些类似的事情:

      <?php $_GET['edit'] = mysql_real_escape_string($_GET['edit']); ?>
      <form method="post">
      Name: <input type="text" name="name" value<? if(isset($_GET['edit'])) {echo '="'.person($_GET['edit']) .'"';} ?>/><br>
       ......
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-21
        • 1970-01-01
        相关资源
        最近更新 更多