简体   繁体   English

如何显示两个表中的数据仅用于匹配记录

[英]How to show data from two tables only for matching record

I have two tables.我有两张桌子。 First one stores user information called "users"第一个存储称为“用户”的用户信息

| user | password | email           |
|:---- |:--------:| ---------------:|
| user1  | pass1  | email@email.com |
| user2  | pass1  | email@email.com |
| user3  | pass1  | email@email.com |

and second "materials" and it stores information about what every user has和第二个“材料”,它存储关于每个用户拥有什么的信息

| user | lumberjack| farmer etc        |
|:---- |:---------:| -----------------:|
| user1| 10        | 20                |
| user2| 20        | 50                |
| user3| 30        | 40                |

I want to get data from 2nd tables but only for specific user.我想从第二个表中获取数据,但只针对特定用户。

I tried this but it shows materials for every user that is in both tables.我试过这个,但它显示了两个表中每个用户的材料。 And what i want to do is to show one row from 2nd table that has same user name as logged.我想要做的是显示第二个表中与记录的用户名相同的一行。 For example if user1 is logged i want to show that he has 10 lumberjacks and 20 farm, if user2 is logged then 20 lumberjacks 50 farms etc.例如,如果用户 1 已登录,我想显示他有 10 个伐木工人和 20 个农场,如果用户 2 已登录,则有 20 个伐木工人和 50 个农场等。

$sql = "SELECT lumberjack, stonemanson, farmer FROM materials JOIN users ON materials.user = users.user  ";}

  $res = $conn->query($sql);

  if ($res->num_rows > 0)
  {
    while ($row = $res->fetch_assoc())
    {
      echo "Lumberjack: " . $row["lumberjack"]. " Stonemanson: " . $row["stonemanson"]. " Farmer: " . $row["farmer"].  "<br>";
    }
  }

Concerning your query add WHERE clause to it.关于您的查询,向其中添加WHERE子句。

Eg if the user id is 26 SQL query will be例如,如果用户 id 是26 SQL 查询将是

SELECT lumberjack, stonemanson, farmer FROM materials JOIN users ON materials.user = users.user WHERE users.user=26

And checking your table structure, if you will not need any data from the users table then you shouldn't bother to use JOIN并检查您的表结构,如果您不需要用户表中的任何数据,那么您不应该费心使用JOIN

this will also work fine and it'll be faster SELECT lumberjack, stonemanson, farmer FROM materials WHERE materials.user =26这也能正常工作,而且速度会更快SELECT lumberjack, stonemanson, farmer FROM materials WHERE materials.user =26

NB: using query() makes your code vulnerable to SQL injection You should use Mysqli or PDO prepared statement.注意:使用query()会使您的代码容易受到 SQL 注入攻击您应该使用 Mysqli 或 PDO 准备好的语句。

Stackoverflow has many answers on that. Stackoverflow 对此有很多答案。 So after you have resolved your issue, then start read on SQL injection and use of PDO or Mysqli prepared statement所以在你解决了你的问题之后,然后开始阅读SQL 注入PDO 或 Mysqli 准备语句的使用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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