1

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.

0

4 Answers 4

1

Try a subquery

SELECT * FROM messages WHERE to_user in (SELECT username FROM Users1 WHERE email = '$param')
Sign up to request clarification or add additional context in comments.

Comments

1

You can join the queries into one:

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

Comments

1

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.

Comments

0

You can combine the two queries into one.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.