简体   繁体   中英

Get the question's id

I'm trying to code a site like Stackoverflow. Not the same. Just the algorithm.

In the site, there is a question-answer system. My question is about "answering the question". How can I get the question's id? Questions and answers are in different tables.

I might be coding the site in the wrong way. If I do that, please tell me. Note: I'm not a native speaker. I can made some mistakes while I'm asking.

In the site, there is a question-answer system. My question is about "answering the question". How can I get the question's id? Questions and answers are in different tables.

I am not sure of how StackOverflow is coded, but usually this type of thing is done using a "questions" table with structure like:

id   |   title   |    question  | .....

and then an "answers" table that references the questions in the first table, such as

id   |   question_id  |  answer  | .....

So, the answers with id 5, 6, 22 and 30 may all reference the question with id 5.

To see all responses to question 25, for instance you will then query the DB using

SELECT answer FROM answers WHERE question_id = 25

Update

To get the question number you'll probably read it from the parameters passed to the page.

For instance, the URL for question 25 will be something like:

www.example.com/showQuestion.php?id=25

In your code you will do:

$questionID = (int)$_GET['id']; // IMPORTANT: use (int) to sanitize input!!!

And then

$result = mysql_query("SELECT answer FROM answers WHERE question_id = ".$questionID);

StackOverflow uses a different way to get the id, by doing:

www.stackoverflow.com/questions/<the id of the question>/<the-title-of-the-question>

So, for instance, this page is:

http://stackoverflow.com/questions/5282563/get-the-questions-id

The engine probably splits the address by / and then gets the 2nd token which is the id (5282563 in this case). The last part is called a slug .

If you meant "get the question by the id", then it should be something like:

SELECT question_id, title, body FROM question WHERE question_id = the_id

Assuming that your question has id , title and body , and:

  • your questions table is called question
  • the_id is the id of the question you're trying to fetch

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