douguachan2879
2017-04-20 20:03
浏览 295
已采纳

从owner_id的表中获取用户

I'm writing a snippet in PHP that get all images from a table "pic" with 3 columns :

  1. id
  2. owner_id
  3. name

So I wrote this :

try
{
    $db = new PDO($DB_DSN, $DB_USER, $DB_PASSWORD);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // to get an exception when caught an error :)
} catch (PDOException $e) {
    print "Erreur !: " . $e->getMessage() . "<br/>";
    die();
}

$find_pic = $db->prepare("SELECT * FROM camagru_jgengo.pic ORDER BY id DESC");
$find_pic->execute();
$pics = $find_pic->fetchAll();

And I made a while to show all images from my database. But I've got a problem, under the image I would like to show the username of the guy who sent the image.

And I've a table 'user' with columns : id and login.

I would like my script to make an array with key (id) => (login). But I tried a lots of things, I don't succeed to build it. Or if you have a better idea I'm all open :)

Thank you

图片转代码服务由CSDN问答提供 功能建议

我正在用PHP编写一个片段,从3个列的“pic”表中获取所有图像:

  1. ID
  2. owner_id
  3. 名称 < p>所以我写了这个:
      try 
     {
     $ db = new PDO($ DB_DSN,$ DB_USER,$ DB_PASSWORD); 
     $ db-&gt;  setAttribute(PDO :: ATTR_ERRMODE,PDO :: ERRMODE_EXCEPTION);  //在遇到错误时获取异常:)
    } catch(PDOException $ e){
     print“Erreur!:”。  $ e-&gt; getMessage()。  “&lt; br /&gt;”; 
     die(); 
    } 
     
     $ find_pic = $ db-&gt; prepare(“SELECT * FROM camagru_jgengo.pic ORDER BY id DESC”); 
     $ find_pic  - &gt; execute(); 
     $ pics = $ find_pic-&gt; fetchAll(); 
       
     
     

    我花了一些时间来显示数据库中的所有图像 。 但是我有一个问题,在图像下我想显示发送图像的人的用户名。

    我有一个表'用户'列 :id和login。

    我希望我的脚本用key(id)=&gt;创建一个数组 (登录)。 但是我尝试了很多东西,我没有成功构建它。 如果你有更好的想法我会全部开放:)

    谢谢

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doufuxi7093 2017-04-20 20:14
    已采纳

    Use a join and you can get all information you want with one query. Roughly:

    SELECT p.*, u.name 
    FROM camagru_jgengo.pic as p
    join users as u on u.id = p.ownerid
    ORDER BY p.id DESC
    

    You'll need to modify the columns to match your actual column/table names. If a picture can be uploaded without an owner you might need to make this a left join.

    已采纳该答案
    打赏 评论
  • duannong1801 2017-04-20 20:14

    I think what need is a JOIN statement, try google for left join, outer join, inner join, right join, otherwise you could do a while loop for images and inside that a select query to fetch the user data.

    打赏 评论

相关推荐 更多相似问题