Sending variables from one PHP page to another

后端 未结 3 1364
长情又很酷
长情又很酷 2021-01-24 17:04

I\'m building a quiz web application that is dynamically generated from a database on my server. I have pretty much implemented all the functionality, the only missing piece is

相关标签:
3条回答
  • 2021-01-24 17:24

    Use $_GET.

    First, you're going to want to change this line

    echo '<a href="quiz.php">' . $row['title'] . '</a><br />';
    

    To something like this:

    echo '<a href="quiz.php?id='.$row['id'].'">' . $row['title'] . '</a><br />';
    

    And then in quiz.php, retrieve the appropriate quiz using $_GET['id'] as your primary key to look it up in the database.

    You should store your quiz title there too (in the db).

    $_GET is appropriate here because you're just using an ID to determine which quiz to display. There's no need for confidentiality here. You would use $_POST when you're submitting form data which alters the database. $_SESSION is useful for storing basic login info and other stuff that must persist across multiple pages for the life of the session, such as wizard forms.

    0 讨论(0)
  • 2021-01-24 17:25

    First of all, tackle one problem at a time first the list of question working then the authentication.

    You should use GET because:

    • $_SESSION is to store things specific to a given user its behaviour and authentication information such as a token.
    • $_POST is for code that modifies the server side (here you only load things from the database).
    • $_GET is to retrieve server-side information which is exactly your case.

    Here loading a question is not something that should be different from one user to another. It will not directly modify something on the server-side. This is why you should use GET. Using something else will work but it is not the proper way to do it.

    So basically what you change is:

    echo '<a href="quiz.php">' . $row['title'] . '</a><br />';
    

    by

    echo '<a href="quiz.php?q_id='.$row['id'].'">' . $row['title'] . '</a><br />';
    

    And in you quizz page you can now know the id of the question (stored by default in $_GET["qid"]) and do whatever you want with it. This of course can be applied to other variables.

    0 讨论(0)
  • 2021-01-24 17:33

    To "send" values from one PHP page to another, you can use sessions or GET variables sent in the url.

    Sessions:

    $_SESSION["quiz_id"] = 1;
    $_SESSION["quiz_title"] = "geography";
    

    URL: mypage.php?quiz_id=1&quiz_title=geography

    $quiz_id = $_GET["quiz_id"];
    $quiz_title = $_GET["quiz_title"];
    

    To send values from the client to the server, you will have to use an HTML form or AJAX.

    0 讨论(0)
提交回复
热议问题