简体   繁体   English

通过链接关联数据库和PHP

[英]Relate database and PHP through links

I'm doing a code where the main page has titles of some exercises: 'Exercises.php' (stored in a Mysql database) and depending on what title the user clicks (with links), I want the title and the question itself in another page: 'question.php'. 我正在执行一个代码,其中主页包含一些练习的标题:“ Exercises.php”(存储在Mysql数据库中),并且根据用户单击的标题(带有链接),我希望标题和问题本身位于另一页:“ question.php”。 The questions will also be taken from the database. 这些问题也将从数据库中获取。 Im trying to use a GET parameter in the exercise link with the id of the exercise. 我试图在练习链接中使用带有练习ID的GET参数。 Then in 'question.php', get the exercise with that id from the database. 然后在“ question.php”中,从数据库中获取具有该ID的练习。

This is some of the code that I've done so far but I'm stuck. 这是到目前为止我已经完成的一些代码,但是我遇到了麻烦。 Could you help me? 你可以帮帮我吗? Thank you. 谢谢。

Exercises.php – In here I have all of the titles of the exercises displayed. Exercises.php –在这里,我显示了所有练习的标题。

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

$conn = new mysqli($servername, $username, $password, $dbname);


$sql = "SELECT * FROM exercises";
$result = $conn->query($sql);

?>

<?php
while($row = $result->fetch_assoc())
{
    ?>
    <tr>
        <td><?php echo $row["exercise_id"]; ?></td>
        <td><a name="search" href="http://localhost/PHP%20Pages/2.php" target="_blank"><?php echo $row["title"]; ?></a></td>
        <td><?php echo $row["difficulty"]; ?></td>

    </tr>
    <?php
}
?>

question.php question.php

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

$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT * FROM exercises"; /*Select from table name: exercises*/
$result = $conn->query($sql); /*Check connection*/


    $result = $conn->query($sql);
    while($row = $result->fetch_assoc()) {
        echo $row["exercise_id"] . ". " .  $row["title"] . $row["text"] . "<br>";
    }
}
?>

If you want to get the excericise_id from excercise.php you can change your href like this 如果您想从excercise.php获取excericise_id ,则可以像这样更改href

<a href="question.php?id=<?php echo $row["exercise_id"] ?>" role="button" class="btn">Add Topic</a></td>

And you can get that exercise id in your question.php page like this 您可以像这样在您的question.php页面中获得该练习ID

$id=$_GET['id'];

I would like you to suggest you to keep your db connection in separate file and try to include and use. 我希望您建议您将数据库连接保留在单独的文件中,并尝试包含和使用。 that is not the good way to write database connection in every page. 这不是在每个页面中编写数据库连接的好方法。

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

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