Executing an SQL query inside another SQL query

Well, I guess the name is not the best title, but let me explain my problem: I am creating a website on which I want people to post (anyway), and I have to show their gravatar profile profile, so this is what I did :

<?php 
            function get_gravatar( $email, $s = 80, $d = 'mm', $r = 'g', $img = false, $atts = array() ) {
                $url = 'https://www.gravatar.com/avatar/';
                $url .= md5( strtolower( trim( $email ) ) );
                $url .= "?s=$s&d=$d&r=$r";
                if ( $img ) {
                    $url = '<img src="' . $url . '"';
                    foreach ( $atts as $key => $val )
                        $url .= ' ' . $key . '="' . $val . '"';
                    $url .= ' />';
                }
                return $url;
            }
            require("db.php");
            $sql = "SELECT * FROM posts ORDER BY date DESC";
            foreach ($db->query($sql) as $row) {
                // var_dump($row);
                $user = $row['user_id'];
                $sql_user = "SELECT email FROM users WHERE id = $user";
                foreach ($db->$sql_user as $row_user) {
                    var_dump($row_user);
                    echo "<img src=\"".get_gravatar($row_user['email'])."\"/>";
                }
                echo "<h2>".$row['title']."</h2><br/>";
                echo "<p>".$row['content']."</p><br/>";
            }

But it doesn’t work (well, it works, but it doesn’t show me the user profile picture, only the message). So, I think the problem is that I cannot call the variable twice $db, but I'm not sure, so m = why I ask if there is a way to fix my problem or select 2 tables at the same time.

+4
source share
5

$sql="SELECT u.email "
                    . "FROM posts AS p "
                    . "LEFT JOIN users AS u "
                    . "ON u.id=p.user_id "
                    . "ORDER BY p.date DESC";
+2

join

SELECT * FROM users join posts  on users.id =Posts.user_id ORDER BY date DESC
+1

You can just use joins

The JOIN clause is used to join rows from two or more tables based on a related column between them.

+1
source

you don't apply the query to sql string in the second foreach

  foreach ($db->query($sql_user) as $row_user) {
+1
source

see your second foreach that you skip to put a query function

foreach ($db->query($sql) as $row) {



foreach ($db->query($sql_user) as $row_user) {
+1
source

Source: https://habr.com/ru/post/1673384/


All Articles