mysqli根据行ID值

时间:2015-06-29 20:17:14

标签: php mysql database mysqli

我需要根据其他表中的值显示一行中的文本,我将逐步解释......一切都非常清晰。

名为“links”的表有一行名为“title_id”

来自“links”的这一行“title_id”在名为“id”的行中名为“titles”的其他表中具有THE SAME值。

表“标题”有另一行称为“标题” - 而且这是我需要以这种方式显示...

a href = .... /> TABLE链接行title_id =到TABLE标题行id - >在这里显示表标题行标题(基于表链接中的行title_id)< / A ...

我希望你能理解,结果必须是(a href = ...> TEXT MOVIE TITLE< / a>)

这是基本代码,我需要更改(我已评论部分需要更改):

    <?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "dbname";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 

    $sql = "SELECT id, label, title_id, season, episode, approved FROM links WHERE approved = 1 order by id desc LIMIT 30 OFFSET 1";
    $result = $last_id = $conn->query($sql);


    if ($result->num_rows > 0)
     {
        echo "<table><tr><th>ID</th><th>Audio</th><th>URL</th><th>Temporada</th><th>Episodio</th><th>Aprobado</th></tr>";
        // output data of each row
        while($row = $result->fetch_assoc()) {
            echo "<tr><td>".$row["id"]."</td><td>".$row["label"]."</td>";
            echo "<td>";
            if (empty($row['episode'])) {
         echo "<a href=";
         echo '/peliculas-online/'.$row["title_id"];
         echo ">HERE MUST HAVE THE VALUE FROM TABLE titles -> row title - based on $row["title_id"] </a>";
// -------------------------
        }
        else {
        echo "<a href=";
         echo '/series-online/'.$row['title_id'].'/seasons/'.$row['season'].'/episodes/'.$row["episode"];
         echo ">HERE MUST HAVE THE VALUE FROM TABLE titles -> row title - based on $row["title_id"] </a>";
// -----------------------------------
            }
            echo "</td>";
            echo "<td>".$row["season"]."</td><td>".$row["episode"]."</td><td>".$row["approved"]."</td></tr>";


        }
        echo "</table>";
    } else {
        echo "0 results";
    }
    $conn->close();
    ?>

1 个答案:

答案 0 :(得分:1)

您只需稍微修改一下您的查询即可获得此信息。您可以在这些ID上加入标题:

SELECT l.id, l.label, l.title_id, t.title, l.season, l.episode, l.approved 
FROM links l
JOIN titles t
ON l.title_id = t.id
WHERE approved = 1 
ORDER by id DESC
LIMIT 30 OFFSET 1

然后你可以像以前一样调用你的变量;相同的查询将有row['title']

详细了解MySQL Joins

要在您的脚本中获取此内容,只需替换此行:

echo ">HERE MUST HAVE THE VALUE FROM TABLE titles -> row title - based on $row["title_id"] </a>";

用这个:

echo '>'.$row['title'].'</a>';