简体   繁体   English

2表和PHP的SQL查询

[英]sql query from 2 tables and php

I have a simple php code that fetches data from a sql table. 我有一个简单的php代码,可从sql表中获取数据。

TABLE 1 表格1

date_time 
name

and another table which store name(same as TABLE1) and picture link. 另一个表存储名称(与TABLE1相同)和图片链接。

TABLE 2 表2

name
pic

PHP 的PHP

$db = new PDO("mysql:host=$host;dbname=$dbname", "$username", "$password");
$sql = "select * from table1";
foreach ($db->query($sql) as $row) {
echo '<span class=name>'.$row['name'].'</span>';
echo "<img src=".$row['pic']." width='25px' height='25px'/>";
$db = null;
}

What i want is to be show the picture of the name from TABLE 2( $row['pic'] ) according to name in TABLE 1. How the sql statement and the php code should be in order to achieve this? 我想要的是根据表1中的名称显示表2( $row['pic'] )中名称$row['pic'] 。如何实现sql语句和php代码才能实现此目的? I run a sql statement in phpMyadmin and got it,but couldnt translate it in php code. 我在phpMyadmin中运行了一条sql语句并获得了它,但是无法将其翻译成php代码。

select table1.name,table2.pic from table1,table2 where table1.name=table2.name;

How about using JOIN : 如何使用JOIN

SELECT table1.name, table2.pic 
FROM table1 
INNER JOIN table2 
  ON table1.name = table2.name

try this, use as keyword to alias your column names, so that you can get 'name' and 'pic' index in the loop. 尝试此操作,使用as关键字为列名加别名,以便您可以在循环中获取'name''pic'索引。

select 
   table1.name as `name`,
   table2.pic as `pic` 
from table1, table2 
where table1.name = table2.name;

a better way to do it use joins 一种更好的方法是使用联接

select 
   `table1`.`name` as `name`,
   `table2`.`pic` as `pic` 
from `table1`
     inner join `table2`
     on `table1`.`name` = `table2`.`name`;

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

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