User007
User007

Reputation: 41

Use Query Result Row in Another Query

I'm trying to use the row from a query in another query.

This query correctly displays the username of the user currently signed in:

$param = $fgmembersite->UserEmail();

$query = mysqli_query($con, "SELECT username FROM Users1 WHERE email = '$param'
");

while ($row = mysqli_fetch_array($query)){
echo $row['username'] ;
    }

I'm trying to find a way to use $row['username'] in another query something like...

$sql = mysqli_query($con, "SELECT * FROM messages WHERE to_user = '" . $row['username'] . "' ");

This doesn't give me a coding error, but it doesn't work. The username row obviously can't be taken from a separate query the way I'm attempting.

I have tried every combination I can think of but nothing has worked for me. Any help greatly appreciated.

Upvotes: 1

Views: 963

Answers (4)

MKB
MKB

Reputation: 281

Well you should place your second query inside while:

while ($row = mysqli_fetch_array($query)){
  echo $row['username'] ;
  $sql = mysqli_query($con, "SELECT * FROM messages WHERE to_user = 
    '" . $row['username'] . "' ");
}

Now loop ends when mysqli_fetch_arrray returns NULL and that NULL you are trying to insert into second query.

Upvotes: 1

Jonathan Kuhn
Jonathan Kuhn

Reputation: 15301

You can join the queries into one:

SELECT `messages`.*
FROM `messages`
    JOIN `Users1`
        ON `Users1`.`username`=`messages`.`to_user`
WHERE
    `Users1`.`email`='$param'

Upvotes: 1

Goontracker
Goontracker

Reputation: 234

You can combine the two queries into one.

SELECT * FROM messages WHERE to_user = (SELECT username FROM Users1 WHERE email = '$param')

Upvotes: 0

Jaycee
Jaycee

Reputation: 3118

Try a subquery

SELECT * FROM messages WHERE to_user in (SELECT username FROM Users1 WHERE email = '$param')

Upvotes: 1

Related Questions