简体   繁体   中英

Cross relating PhP / Mysql field in SELECT command from multiple tables

I currently have two tables, one is Members (storing userid numbers, usernames, passwords) and one is Wire (which stores user submitted data: category, contents, date, the user number who contributed - automatically fetched from a current session variable called $_SESSION['user_id'].)

Once submitted, just for examples sake, a line from the Wire table might look like:

category | contents | date | userid

Beef | it's good | 10/08/213 | 5

So user number 5 selected beef and wrote "it's good" on October 5th. In the separate Members table, user 5's username is let's say John.

I then have a get.php that pulls up this info and puts it into a table for all to see.
I'm rather new, so this might be easy, but my question is in my get.php, how do I get it to replace "5" and put in "John?" I looked up join commands but I'm not sure how to relate it to my code. Here's the section of my get.php that creates the table:

$result = mysqli_query($con,"SELECT * FROM wire order by date DESC");

echo "<table border='1'>
<tr>
<th>Category</th>
<th>Contents</th>
<th>Date/Time</th>
<th>Username</th>
</tr>";

while($row = mysqli_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['category'] . "</td>";
  echo "<td>" . $row['contents'] . "</td>";
  echo "<td>" . $row['date'] . "</td>";
  echo "<td>" . $row['userid'] . "</td>";  //change 5 to John
  echo "</tr>";
  }
echo "</table>";

If it helps, the logins are all managed by the system in this tutorial: http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL

Any help would be appreciated!

Try something like this (don't have time to try it):

 "SELECT category, contents, date, username 
FROM wire join members on wire.userid=memebers.userid" order by date DESC"

This should give you an array like the one you have but instead of $row['userid'] you will use $row['username'];

You will want to join the two table together so you can get the Name in the same result.

$result = mysqli_query($con,"SELECT opwire.*,members.username FROM opwire 
          JOIN members ON opwire.userid=members.id order by date DESC");

Then you can echo the name by changing the userid to the name

echo "<td>" . $row['userid'] . "</td>";  // change this
echo "<td>" . $row['username'] . "</td>";  // to this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM