Silverfall05
Silverfall05

Reputation: 1127

PHP: how to read values from functions that return array

So I have form:

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

and

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

So Function returns an array, How can I get from this function to display me only: 'name' / 'sname' / 'age' in each of input value

Upvotes: 1

Views: 374

Answers (4)

Stefan Gi
Stefan Gi

Reputation: 450

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

But you should escape ur Parameters before using them in your sql statement! At least do something like:

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

Upvotes: 0

Dmytro Zarezenko
Dmytro Zarezenko

Reputation: 10686

At first use mysql_fetch_assoc for use letter keys.

Then you can do so in latest versions of PHP:

person($id)['name']

Or define separate array in older versions of PHP:

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

Upvotes: 4

WatsMyName
WatsMyName

Reputation: 4478

$per=person('12');

to get name name, sname, age

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

Upvotes: 0

RippeR
RippeR

Reputation: 1472

It's just like a normal array, so you can use [id]. If you use mysql_fetch_row it must be numbers from 0 to n-1 where n is number of items in array in order that you did in query. If you have mysql_fetch_assoc you can use $test['name'], $test['sname'], $test['age'].

$test = person(5);

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

Upvotes: 0

Related Questions