简体   繁体   中英

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'. 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. Then in 'question.php', get the exercise with that id from the database.

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.

<?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

<?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

<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

$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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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