我有两个表第一个 researchprojects ,其中包含 Publications ,这些是逗号分隔的numberes,在另一个表 publi 我有< em> Pub_id 其中相同的值不是逗号分隔,而其他列如 Pub_year 我的问题是如何链接这两个表并输出 Pub_id ,< em> Pub_year 值?
researchprojects 表
Publications
800, 900, 1000
1000, 1200, 1300
publi 表
Pub_id Pub_year
800 2015
900 2016
1000 2017
1200 2016
1300 2012
答案 0 :(得分:0)
以下是您可以做到的:
例如:
在你的情况下,你需要像这样使用两个表结构:
Table : researchprojects => id,publications
Table : publi => publi_id,publi_year
您的案例:
在您的情况下,您在一行中提到的所有id's
为:
researchprojects
|
V
---------------------------
publications
800,900,1000
---------------------------
publi
|
V
---------------------------
publi_id publi_year
800 2012
800 2013
900 2014
900 2015
1000 2016
1000 2017
---------------------------
显示表数据输出的代码:
<?php
// Assuming that $publications will hold all fetched values from researchprojects table
// Also assuming that $publi will hold all fetched data from publi table
$publi_ids = explode(",",$publications[0]['publications']);
//Now you have all ids in array in $publi_ids
//So moving forward with the code
foreach ($publi_ids as $publi_id) {
echo "<h1>".$publi_id."</h1>";
$id = $publi_id;
$query = mysqli_query($mysqli,"SELECT * FROM publi WHERE publi_id='$id'");
$publi_data = array();
while ($rows = mysqli_fetch_array($query)) {
$publi_data[] = $rows;
}
foreach ($publi_data as $publi_row) {
echo "Year :".$publi_row['publi_year']."</br>";
echo "</br></br></br>";
}
echo "</br></br></br></br>";
}
?>
输出:
800
Year : 2012
Year : 2013
900
Year : 2014
Year : 2015
1000
Year : 2016
Year : 2017
答案 1 :(得分:0)
我已经解决了这个问题!
$query = "SELECT * FROM researchprojects";
$result = mysqli_query($con, $query);
while ($val = mysqli_fetch_array($result))
{
$Id = $val['Id'];
$Publications = $val['Publications'];
$Publication_seprated = explode(',', $Publications);
foreach($Publication_seprated as $Publication_seprated)
{
$query2 = "SELECT * FROM publi WHERE Pub_id = '$Publication_seprated'";
$result2 = mysqli_query($con, $query2);
while ($val2 = mysqli_fetch_array($result2))
{
$pub_id = $val2['pub_id'];
$pub_year = $val2['pub_year'];
echo $pub_year;
} // while loop
} // foreach
} // while loop
答案 2 :(得分:-2)
创建一个数组,它将以键和值对的形式将pub_id和pub_year存储在数组中
<?php
$pub = [800 => 2015, 900 => 2016, 1000 => 2017];
foreach ($pub as $pubId => $pubYear)
{
echo "<td>{$pubId}, {$pubYear}</td>";
}
?>