wlraider70
wlraider70

Reputation: 186

Store SQL output in variable

I'm a big noob here, so I'm trying to figure it out as a I go.

I want to take a SQL request for "id, fist and last" and store each of those in a variable. the next half of the code would be doing things with those variable.

The lower statements are simply to see if the var is begin assigned... Apparently it is not, but I get no error, just the blank lines. How can I get the info in a set to do something with?

$newIDs = mysql_query("SELECT per_ID, per_FirstName, per_LastName FROM person_per WHERE DATE_SUB(NOW(),INTERVAL 6 MONTH)<per_FriendDate ORDER BY per_FriendDate DESC") or die(mysql_error());



while($row = mysql_fetch_assoc($newIDs)){
    echo $row ['per_ID'] = $per_ID;
    echo $row ['per_FirstName'] = $per_FirstName; 
    echo $row ['per_LastName'] = $per_LastName;
    //below is for testing purposes only
    echo $per_FirstName;
    echo "<br/>";

}

print $per_ID;
echo $per_LastName;

Upvotes: 0

Views: 114

Answers (3)

Alex K
Alex K

Reputation: 15898

I'm thinking you wanted something more like this for your test:

while ($row = mysql_fetch_assoc($newIDs)) {
    $per_ID = $row['per_ID'];
    $per_FirstName = $row['per_FirstName'];
    $per_LastName = $row['per_LastName'];
    // below is for testing purposes only
    echo $per_FirstName;
    echo "<br/>";
}

When you actually want to keep all the results from your query, you'll need to do something like:

$rows = array();
$i = 0;

while ($row = mysql_fetch_assoc($newIDs)) {
    $rows[$i] = $row;
    // below is for testing purposes only
    echo $rows[$i]['per_LastName'];
    echo "<br/>";

    $i++;
}

Also, you should note that mysql_fetch_assoc() is actually a deprecated PHP function, according to the manual page: http://php.net/manual/en/function.mysql-fetch-assoc.php

Upvotes: 1

Mike Dinescu
Mike Dinescu

Reputation: 55760

It looks like your problem is in these statements:

echo $row ['per_ID'] = $per_ID;
echo $row ['per_FirstName'] = $per_FirstName; 
echo $row ['per_LastName'] = $per_LastName;

The equals sign there assigns the value of variable $per_ID (which at that time is unassigned) to the array. That's not what you want.

Instead you probably want something like this:

$per_ID = $row ['per_ID'];

Things get further complicated by the fact that you have a while loop in which you would keep writing to the same three variables. So after the loop ends you would only have the value of the last set of fields.

Upvotes: 0

user557846
user557846

Reputation:

echo $row ['per_ID'] = $per_ID;

should be

$per_ID=$row['per_ID'];

you echo of $per_ID; should then work

As its in a loop you will overwrite $per_ID each time and end up wit the last value.

Upvotes: 0

Related Questions