Problem: Taking information from...

begamer26

New Member
Messages
24
Reaction score
0
Points
0
I'm trying to take information from one mysql table and put it into another.

It's VERY hard to explain but here's my code:
PHP:
                      $con = include('dbc.php');
                      mysql_select_db("tb_begamer, $con");
                      
                      $user = mysql_query("SELECT user FROM users");
                      $pic = mysql_query("SELECT picture FROM images WHERE username = $user");
                      echo('<img src="' . $pic . '" height="140" />');
 

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
It's not as hard as you think. Start with a statement in English describing the data you want (such as "The picture for the user with a given ID."). Note that you're not putting data from one table into another (which would involve an INSERT statement), you're using data from one table to filter rows from another (i.e. selecting data from one table based on restraints on another, related table). What you're looking for is the JOIN clause.

Code:
SELECT picture 
  FROM images 
    JOIN users ON images.username=users.user
  WHERE ...

One thing you've left out of your sample is how you're picking a user. That is, you've no WHERE clause when selecting from the `users` table. Consequently, the query will return all usernames in the `users` table.

Queries return results, not strings. To get a username from $user, you have to use a function to retrieve a row from it, such as mysql_fetch_row. Rather than making that change, you should switch to PDO. The mysql driver is quite outdated. If you want a PDO tutorial, try "Writing MySQL Scripts with PHP and PDO".

PHP:
$getImage = $db->prepare('SELECT picture 
  FROM images 
    JOIN users ON images.username=users.user
  WHERE users.id = ?');
$getImage->execute(array($id));
$pic = $getImage->fetchColumn();

Lastly, separate display from database access. The code that fetches the image URL shouldn't also generate the <img> tag. This is a consequence of the single responsibility principle and part of separation of concerns. Read up on the Model-View-Controller pattern for more on a better approach.
 
Last edited:
Top