Home and Learn: PHP Programming Course
To add new questions to the database, we have this HTML form:
This is fairly straightforward. You type your question into the textbox at the top, and type your three options into the textboxes below that. Click the Set this Question button and it will add it to the database.
The PHP code for all this is as follows:
PHP code - adding a new question (opens in a new browser tab as a text file)
The HTML uses four INPUT TYPES (Text) and a SUBMIT button. The FORM itself
is has the METHOD as GET, and the ACTION is to send it back to setQuestion.php
The first textbox has a MAXLENGTH attribute set. We have this as a value of 40, but you can change this, if you want. The NAME properties for the textboxes are question, AnswerA, AnswerB, and AnswerC. We'll need these names to grab the values entered into the textboxes.
n the PHP code, we first check that the Sub1 button is set. We then place the values from the HTML form into variables:
$question = $_GET['question'];
$answerA = $_GET['AnswerA'];
$answerB = $_GET['AnswerB'];
$answerC = $_GET['AnswerC'];
After connecting to the server and database, we construct some SQL:
$SQL = "INSERT INTO tblsurvey (Question, OptionA, OptionB, OptionC) VALUES (?,?,?,?)";
We're trying to access four fields in our database table Question, OptionA, OptionB, and OptionC. We want to INSERT VALUES. There are four question marks between the round brackets of VALUES, one for each of the four fields.
To bind the parameters, we have this:
$stmt->bind_param('ssss', $question, $answerA, $answerB, $answerC);
The first parameter uses four letter S's, one for each of the string values going into the table.
Once we execute this statement, we print out a friendly message, to tell the user that the question has been added to the database.
That's all you need to add a new question to the database.
And that's it for the survey walkthrough. Some of it, like adding a new question, is fairly straightforward, while some of it is quite complex, if you're a beginner. But study the code, and hopefully you'll gain a greater insight into how it all works. Try modifying it for your own needs, and see how you get on. Good luck!
Email us: enquiry at homeandlearn.co.uk