E.Nathan E.Nathan - 3 months ago 4x
SQL Question

Use array results from database as php variables

The application I'm building requires some users to be linked to eachother.

There will be users and mentors. The database field "mentor_link" has a value. This value determines which users the mentor is linked to.

What I'm trying to do is search the database for the users with a certain "mentor_link" value and save their usernames as php variables to be used later.

Using json_encode() AND print_r simply displays something that looks like this:


What I'm looking for is to target each username and save it as a variable. For example: $user1 = dave; $user2 = ely; etc etc.

All the other examples I've found only allow me to display it the same way as above.

My code is as follows:

$stmt = $user_home->runQuery("SELECT userName FROM tbl_users WHERE mentor_link=101");

$result = $stmt->fetchAll();
echo json_encode($result);

The database is connected fine and I'm able to pull single values based on the users details but I can't figure out how to get info on other users and display it/save it as a variable.

Oh and I'm using PDO to connect to the database.


After this line:

$result = $stmt->fetchAll();

You can do anything with that data



$user1 = $result[0]; 
$user2 = $result[1];


echo $user1['userName'];//dave
echo $user2['userName'];//ely