2017-01-10 35 views
0

值我是新来的SQL和我有2代表与这些列:从表ID失去在SQL

table structures__|id|name|nation_id|image| 

table nations______|id|nation| 

“nation_id”列链接到nations's表并返回nations's表“id”列。我想从结构中进行查询,从“名称”和“图像”列中获取值,并获得与nation_id相关联的国家。

但在我的代码中,各国的id列最终成为结构表的id。我仍然能够从“名称”中获得正确的值,但是因为我需要原始结构“id”才能获得正确的“图像”。

这是我使用的代码:

$nation = mysqli_real_escape_string($conn, $_GET["nation"]); 
$nameN = mysqli_real_escape_string($conn, $_GET["nameN"]); 

$sql = "SELECT * FROM structures 
LEFT JOIN nations ON structures.nations_id = nations.id 
WHERE nations_id LIKE '$nation' and nations.nation like '$nameN'"; 
+1

** WARNING **:当使用'mysqli'你应该使用[参数化查询(http://php.net/ manual/en/mysqli.quickstart.prepared-statements.php)和['bind_param'](http://php.net/manual/en/mysqli-stmt.bind-param.php)将用户数据添加到您的查询中。 **不要**使用手动转义和字符串插值或串联来实现此目的,因为如果您忘记正确地转义某些内容,您将创建严重的[SQL注入漏洞](http://bobby-tables.com/)。 – tadman

回答

0
SELECT s.*, n.nation 
FROM structures AS s 
JOIN nations AS n ON s.nation_id = n.id 
WHERE n.id = '$nation' 
AND n.nation = '$nameN' 
+0

它现在的作品,非常感谢! – Adato