php - 从表1中获取id与表2匹配

标签 php mysql

我是 php 新手,我知道我想做什么,但我不知道如何执行它们

我在 mysql 中有 2 个表 表 1 包含:

ID|Name|AboutMe|Specialisation
Example:
101|Andrew|handsome|drawing
102|Jane|pretty|drawing
103|Daniel|cute|swimming

table 2 contains
ID|Link|Title
101|//image1.jpg|Drawing in the dark
102|//image2.jpg|Drawing in me
103|//image3.jpg|Fish swimming

我想在我的网站运行后显示一些链接到特化的图像。

我所拥有的东西的流程 1)

// get all the ID with drawing as specialisation // will return 2 rows
select ID FROM table1 WHERE Specialisation = "Drawing";
id = ID

2) 从匹配的每一行中,获取 ID 以获取表 2 中的链接,如下所示

// get row of the links from the userid
Select * FROM userdatafiles WHERE ID = id
store the links into a variable and send to my jquery to display.

所以基本上获取与绘图匹配的每一行的 id,并使用该 id 从表 2 中找到相同的 id 并获取链接,并将其作为结果发送到 jquery。

由于我必须发送很多行并且需要使用数组和循环,所以我不确定如何做到这一点。有人可以指导我做我正在做的事情吗?谢谢!

更新:

jquery:

$.ajax({
    type: "POST",
    //dataType: "json",
    url: "CMS/PHP/displayFeatThumbs.php",
    success: function(data) {
            alert(data[0]);
    }
});

PHP:

<?php
include 'dbAuthen.php';
$sql = 'SELECT * FROM userdatafiles JOIN users ON userdatafiles.UserID = users.UserID WHERE Specialisation = "Interactive Art & Technology"';

$result = mysqli_query($con,$sql);


if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        echo $links[] = $row["Link"];           
    }
} else {
    echo "0 results";
}
?>

不知道如何在jquery上显示数组索引,尝试了alert(data[0]),alert(data.links[0]);

最佳答案

您可以使用自然联接来连接 2 个或更多表。 查询应如下所示:

SELECT * FROM userdatafiles JOIN table1 ON userdatafiles.id = table1.id WHERE Specialisation = "Drawing"

结果将是一个新表,如下例所示:

表1:id |名称 |日期
表2: id |城市 |国家/地区

结果: 编号 |名称 |日期 |城市 |国家

您可以像这样处理数据:

$result = mysql_query("Your Query");  
while($row = mysql_fetch_object($result)){  
            //Access values with $row->ColumnName  
}

关于php - 从表1中获取id与表2匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26989032/

相关文章:

php - 当我使用 php 将一个表中的一行提交到另一个表时出现错误

php - 如何正确使用mysqli进行查询和防止注入(inject)

c# - 当用户计算机上运行带有MySQL数据库的软件时,我们需要什么?

mysql - Node.js mysql插入多个表

php - 在 Visual Studio 代码中处理 '0 references' 的 php 回调

php - 使用 Doctrine 2.1 在数据库中保存 Zend 日期

php - 多个 Laravel 网站,中央代码库

php - Eloquent BelongsToMany 关系搜索为空

php - 如何在我的 View 中回显查询结果?

php - 如何将此多维数组转换为带有行标题和列标题的数组?