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

从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

  • 写回答

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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 R运行没有名称为"species"的插槽对于此对象类"SDMmodelCV"
  • ¥20 基于决策树的数字信号处理,2ask 2psk 2fsk的代码,检查下报错的原因
  • ¥20 python作业求过程
  • ¥15 wincc已组态的变量过多
  • ¥60 如图:直线与椭圆X轴平行,求直线与椭圆任意一点的相切坐标计算公式
  • ¥50 如何用python使用opencv里的cv::cudacodec::VideoWriter函数对视频进行GPU硬编码
  • ¥100 c#solidworks 二次开发 工程图自动标边线法兰 等折弯尺寸怎么标
  • ¥15 halcon DrawRegion 提示错误
  • ¥15 FastAPI Uvicorn启动显示404
  • ¥15 centos7.9脚本,怎么排除特定的访问记录