Call a Row By Clicking A Button MYSQL/PHP - php

I am creating an online exam. My layout is to show one question at a time and below it is the multiple choice. At the bottom of the multiple choice is a 'Next' button that when click will show the next question.
The questions and multiple choice are stored in a database.
The problem is, the next button functions, but it redirects me to another page. When all I want is to hide the previous question and show the next question when the next is clicked.
This is my code:
db
CREATE TABLE `english` (
`E_QueID` int(11) NOT NULL,
`Question` text NOT NULL,
`A` text NOT NULL,
`B` text NOT NULL,
`C` text NOT NULL,
`D` text NOT NULL,
`E` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
html
<div class="col-sm-8 bt-query">
<br>
<h4><left>Question 1</left> <right><div class="timer" data-seconds-left="20"></div></right></h4>
<br>
<?php
$query="SELECT * FROM english ORDER BY RAND() LIMIT 1";
$result = mysqli_query($conn, $query);
if (!$result) { // add this check.
die('Invalid query: ' . mysqli_error());
}
while ($row = mysqli_fetch_array($result)) {
echo $row['Question']. "<br />";
echo $row['A']. "<br />";
echo $row['B']. "<br />";
echo $row['C']. "<br />";
echo $row['D']. "<br />";
echo $row['E']. "<br />";
}
?>
<br>
<form action="englishq.php" method="get">
<input type="submit" name="next" value="Next">
</form>
</div>
englishq.php
<?php
$hostname = "localhost";
$user = 'root';
$password = '';
$db = 'questions';
//databse connection
$conn = mysqli_connect("$hostname", "$user", "$password", "$db")or die(mysqli_error());
if(isset($_GET['next'])){
$query="SELECT * FROM english ORDER BY RAND() LIMIT 1";
$result = mysqli_query($conn, $query);
if (!$result) { // add this check.
die('Invalid query: ' . mysqli_error());
}
while ($row = mysqli_fetch_array($result)) {
echo $row['Question']. "<br />";
echo $row['A']. "<br />";
echo $row['B']. "<br />";
echo $row['C']. "<br />";
echo $row['D']. "<br />";
echo $row['E']. "<br />";
}
}
?>

Leave the form's action parameter blank, so the form will submit back to the current page. Then use PHP to read the last question submitted and load the next one to display it to the user. You could use a hidden input field to keep track of which question was submitted.
Form code:
<form action="" method="post">
<input type="hidden" name="question_number" value="<?php echo $mynumber; ?>" />
<input type="radio" name="answer" value="A." /><?php echo $answerA; ?> <br/>
<input type="radio" name="answer" value="B." /><?php echo $answerB; ?> <br/>
<input type="radio" name="answer" value="C." /><?php echo $answerC; ?> <br/>
<input type="radio" name="answer" value="D." /><?php echo $answerD; ?> <br/>
<input type="submit" name="next" value="Next">
</form>
PHP code:
if (isset($_POST['question_number']))
{
// Record the last answer
$stmt = $db->prepare("INSERT INTO user_answer_table (answer_field) VALUES (':answer')");
$stmt->bindParams(':answer', $_POST['answer']);
$stmt->execute();
// Load the next question
$stmt = $db->prepare("SELECT * FROM question_table WHERE question_id = :questionid");
$stmt_>bindParams(':questionid',$_POST['question_number']+1);
$stmt->execute();
}

Check if a $_POST contains an answer. If yes, check if it is correct. Give a feedback. On incorrect answer you might ask the same question again, else generate a new random id.
Place a form around the page content, that sends the data back to the same script.
<form action="" type="post">
Give the client the question id.
<input type="hidden" name="qid" value="<?php echo $row['E_QueID';?>">
Inside the loop over the data table generate some radio buttons
<div>
<input type="radio" id="ansA" name="answer" value="A">
<label for="ansA"><?php echo $row['A'];?></label>
</div>
<div>
<input type="radio" id="ansB" name="answer" value="B">
<label for="ansB"><?php echo $row['B'];?></label>
</div>
Add a submit button and close the form tag.

Related

Value not saving after form is submitted

I've created a mysql table with two columns. One is ID and other is Heading. I have a textarea on which I run UPDATE code and whenever someone submits a form its being updated in the datebase column under heading. And that works fine but I want to show the last inputted submit inside my textarea.
My code is showing the last inputted value but when I reset the page it all turns out blank and its not showing anymore. I looked out in datebase and the heading is still there so I don't know why its dissapearing from the front end.
My page:
<?php
$title = 'Admin Panel - Edit';
include '../config.php';
$heading = mysqli_real_escape_string($link, $_REQUEST['heading']);
$sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
if(mysqli_query($link, $sql) == false){
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);
?>
<form action="edit.php">
<?php echo $currentText[0]; ?>
<input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
<input type="submit" value="Submit" name="submit" />
</form>
So for example if I type Aleksa, after submit it will get url like edit.php?heading=Aleksa&submit=Submit. And then when I delete url just to edit.php, the value is missing.
You can test the page here: https://www.easybewussterschaffen.com/admin/edit.php
This is happening, because it's always trying to insert the heading when you refresh the page. You should check to see if the request is GET or the request is POST, and only insert it if they're submitting the form.
Update your form method, specify it to POST, and specifically check the method or check for the existance of $_POST['submit'] as shown below:
<?php
$title = 'Admin Panel - Edit';
include '../config.php';
// Use one of the 2 if statements:
if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Trying to insert a new heading
if (isset($_POST['submit'])) { // Alternative
$heading = mysqli_real_escape_string($link, $_REQUEST['heading']);
$sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
if(mysqli_query($link, $sql) == false){
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);
?>
<form action="edit.php" method="POST">
<?php echo $currentText[0]; ?>
<input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
<input type="submit" value="Submit" name="submit" />
</form>
Alternatively, if you still wish to make a GET request, you should check to make sure that the heading is set:
<?php
$title = 'Admin Panel - Edit';
include '../config.php';
if (isset($_GET['submit'])) {
$heading = mysqli_real_escape_string($link, $_GET['heading']);
$sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
if(mysqli_query($link, $sql) == false){
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);
?>
<form action="edit.php" method="GET">
<?php echo $currentText[0]; ?>
<input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
<input type="submit" value="Submit" name="submit" />
</form>
I did it like this, is this good tho? Its working
<?php
$sql = "SELECT * FROM content";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo '';
while($row = mysqli_fetch_array($result)){
echo $row['heading'];
}
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
?>

inserting multiple sql query's from a table to another table through PHP

I have this table in with some rows and values in it, i get those values in my php page and user selects them and submits the same to insert the selected into another page.
So, here the main catch,
I wrote a sql query with 3 input boxes in which one takes input number from user and multiplies it with other default number in input box 2(which get the value from table1) and prints it out in input box 3.
I wrote JS code for it and it works fine. now i added php to it, in a way that input box 1 takes value directly from php table row and multiplies it with user inserted value in box2 and prints it in box 3
It still works fine even with multiple queries, cause i have made the id value of each box dynamic.
But the problem rises as when i try to submit the three input box values, it works fine for one query/when one row in table1 but when there are multiple queries, it only inserts the first query (3 input box values) and skips the rest of the queries.
My Php , Js, Html code goes as:
<?php
$sql2 = "SELECT * FROM table1 WHERE value= '$value'";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
while($row2 = $result2->fetch_assoc()) {
?>
<input type="number" name="input1" form="checkout" class="input1" id="input1_<?php echo $row2['id']; ?>" value="<?php echo $row2['price']; ?>">
<input type="text" name="input2" class="input2" id="input2_<?php echo $row2['id']; ?>" value="0" >
<input type="text" name="output" class="output" form="checkout" id="output_<?php echo $row2['id']; ?>" value="">
<form method="post" action="submit.php" id="checkout">
<input type="hidden" value="<?php echo $row2["id"]; ?>" name="id"/>
<button type="submit" class="btn btn-primary btn-sm btn-block">
<h4>Submit</h4>
</button>
</form>
The submit page looks like this..
$input1 = $_POST['input1'];
$output = $_POST['output'];
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO table2 (input1, output)
VALUES ('$input1', '$output')";
if ($conn->query($sql) === TRUE) {
}
else {
echo "ERROR" . $sql . "<br>" . $conn->error;
}
Now the problem is , it works fine inserting data from input1 and output boxes into tabll2 when there is only one query in table 1,
but when there are multiple queries in table 1, it only inserts the first query leaving the rest untouched with no error.
Any help is appreciated..
Then main reason is that all the text boxes for input1 field have one name, then at the result there is only one variable $_POST["input1"], so for other text boxes.
You must set an array-like names for your text boxes:
<?php
$sql2 = "SELECT * FROM table1 WHERE value= '$value'";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
?>
<form method="post" action="submit.php" id="checkout">
<?php
while($row2 = $result2->fetch_assoc()) {
?>
<input type="number" name="input1-<?php echo $row2['id']; ?>" form="checkout" class="input1" id="input1_<?php echo $row2['id']; ?>" value="<?php echo $row2['price']; ?>">
<input type="text" name="input2-<?php echo $row2['id']; ?>" class="input2" id="input2_<?php echo $row2['id']; ?>" value="0" >
<input type="text" name="output-<?php echo $row2['id']; ?>" class="output" form="checkout" id="output_<?php echo $row2['id']; ?>" value="">
<?php
}
?>
<input type="hidden" value="<?php echo $row2["id"]; ?>" name="id"/>
<button type="submit" class="btn btn-primary btn-sm btn-block">
<h4>Submit</h4>
</button>
</form>
<?php
}
?>
Then you must set the submit page:
<?php
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql2 = "SELECT * FROM table1 WHERE value= '$value'";
$result2 = $conn->query($sql2);
while($row2 = $result2->fetch_assoc()) {
$input1 = $_POST['input1-'.$row2['id']];
$output = $_POST['output-'.$row2['id']];
$sql = "INSERT INTO table2 (input1, output) VALUES ('$input1', '$output')";
if ($conn->query($sql) === TRUE) {
}
else {
echo "ERROR" . $sql . "<br>" . $conn->error;
}
}
?>

How do I run multiple SQL Queries using "if(isset($_POST['Submit'])){"

Trying to make a CRUD, everything works except my Update function. I feel like the problem is in the second sql query. When I click on submit it just refreshes and the change is gone. Can anyone show me how to find what I need to change/show me what to change?
<head>
<title>Update</title>
</head>
<body>
</form>
<?php
require_once('dbconnect.php');
$id = $_GET['id'];
$sql = "SELECT * FROM dealers where ID=$id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<form action="" method="post">';
echo "Company: <input type=\"text\" name=\"CName\" value=\"".$row['CName']."\"></input>";
echo "<br>";
echo "Contact: <input type=\"text\" name=\"Contact\" value=\"".$row['Contact']."\"></input>";
echo "<br>";
echo "City: <input type=\"text\" name=\"City\" value=\"".$row['City']."\"></input>";
echo "<br>";
echo "<input type=\"Submit\" = \"Submit\" type = \"Submit\" id = \"Submit\" value = \"Submit\">";
echo "</form>";
}
echo "</table>";
} else {
echo "0 results";
}
if(isset($_POST['Submit'])){
$sql = "UPDATE dealers SET CName='$CName', Contact='$Contact', City='$City' where ID=$id";
$result = $conn->query($sql);
}
$conn->close();
?>
Instead of building a form inside PHP, just break with ending PHP tag inside your while loop and write your HTML in a clean way then start PHP again. So you don't make any mistake.
Also you've to submit your $id from your form too.
Try this
<?php
require_once('dbconnect.php');
$id = $_GET['id'];
$sql = "SELECT * FROM dealers where ID=$id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?= $id ?>" />
Company: <input type="text" name="CName" value="<?= $row['CName'] ?>" />
<br>
Contact: <input type="text" name="Contact" value="<?= $row['Contact'] ?>" />
<br>
City: <input type="text" name="City" value="<?= $row['City'] ?>" />
<br>
<input type="Submit" name="Submit" id="Submit" value="Submit" />
</form>
<?php
} // end while loop
echo "</table>";
}
else {
echo "0 results";
}
Note: You are passing undefined variables into your update query. As you are submitting your form you must have to define those variables before you use them.
if (isset($_POST['Submit'])) {
$CName = $_POST['CName'];
$Contact = $_POST['Contact'];
$City = $_POST['City'];
$id = $_POST['id'];
$sql = "UPDATE dealers SET CName='$CName', Contact='$Contact', City='$City' where ID=$id";
$result = $conn->query($sql);
}
$conn->close();
that loop? ID primary key or not?
maybe u need create more key in table dealer like as_id
<input type="hidden" name="idform" value="$as_id">
in statment
if($_POST){
$idf = $_POST['idform'];
if(!empty($idf)){
$sql = "UPDATE dealers SET CName='$CName', Contact='$Contact', City='$City' where as_id=$idf";
$result = $conn->query($sql);
}
$conn->close();
}

Using SELECT from WHILE as value in html input PHP SQL

I am a complete beginner, so please bear with me. This is just a test project I am putting together to try to teach myself some of the basics.
I know that a lot of my commands are outdated and/or susceptible to injection, but I'd rather stick with this for now (many reasons).
I just had a question about trying to use SELECT from WHILE, and figured that out and got it to echo the correct response on the page.
Now, how do I make it echo that as a value for an HTML text box? It won't work, and I've tried to look for typos but I don't know what I am doing, frankly.
I see that the $studentid and $teacherinfo show fine, I presume because they are normal variables.
Can I somehow define two more variables for first name and last name further up in the page so that I do not need to include so much code in each input (and to keep it from being buggy)?
Here is my code for the page. The inputs will be hidden, but I have been making them text boxes for debugging purposes.
<?php
$connection = mysql_connect($serverName, $userName, $password) or die('Unable to connect to Database host' . mysql_error());
$dbselect = mysql_select_db($dbname, $connection) or die("Unable to select database:$dbname" . mysql_error());
$studentid = $_POST['student_id'];
$teacherinfo = $_POST['teacher'];
$result = mysql_query("SELECT `first_name` FROM `students` WHERE student_id = '$studentid'",$connection);
?>
</head>
<body>
<div align="center">
<form method="post" action="vote_post.php">
<h1>Vote for Teacher of the Month</h1>
<h4>(step 2 of 2)</h4>
<h2>Confirm the Information Below</h2>
<h5>Student id: <?php echo $studentid ?></br>
Student first name: <?php
while($row = mysql_fetch_array($result)){
echo $row['first_name'];
}
?>
</br>
Voted for: <?php echo $teacherinfo ?>
</h5>
<input type="text" name="student_id" value="<?php echo $studentid; ?>"/></br>
<input type="text" name="first_name" value="<?php while($row = mysql_fetch_array($result)){
echo $row['first_name'];
} ?>"/>
</br>
<input type="text" name="last_name" value="<?php while($row = mysql_fetch_array($result)){
echo $row['last_name'];
} ?>"/>
</br>
<input type="text" name="teacher" value="<?php echo $teacherinfo; ?>"/></br>
<input type="submit" value="Submit Vote" class="inputbutton"/></br></br></br>
</form>
You can't use while because your query return only one student. You have to use if instead of while. If your query return many students you can use while.
Try this code:
<?php
if($row = mysql_fetch_array($result)){
?>
Student first name: <?php echo $row['first_name'];?>
</br>
Voted for: <?php echo $teacherinfo ?></h5>
<input type="text" name="student_id" value="<?php echo $studentid; ?>"/></br>
<input type="text" name="first_name" value="<?php echo $row['first_name'];?>"/></br>
<input type="text" name="last_name" value="<?php echo $row['last_name'];?>"/></br>
<input type="text" name="teacher" value="<?php echo $teacherinfo; ?>"/></br>
<input type="submit" value="Submit Vote" class="inputbutton"/></br></br></br>
<?php
}
?>
I hope this help.
I tried to build a code that will help you. Remember that you use last_name, but does not return the field in SQL.
</head>
<body>
<div align="center">
<form method="post" action="vote_post.php">
<h1>Vote for Teacher of the Month</h1>
<h4>(step 2 of 2)</h4>
<h2>Confirm the Information Below</h2>
<?php
$connection = mysql_connect($serverName, $userName, $password) or die('Unable to connect to Database host' . mysql_error());
$dbselect = mysql_select_db($dbname, $connection) or die("Unable to select database:$dbname" . mysql_error());
$studentid = $_POST['student_id'];
$teacherinfo = $_POST['teacher'];
$result = mysql_query("SELECT `first_name`,`last_name`,`student_id` FROM `students` WHERE student_id = $studentid",$connection);
while($row = mysql_fetch_array($result)){
echo "<h5>Student id: $row['student_id'] </br>" .
"Student first name: $row['first_name'] </br>" .
"Voted for: $teacherinfo </h5> " .
"<input type='text' name='student_id' value='$row[\'student_id\']' /></br>" .
"<input type='text' name='first_name' value='$row[\'first_name\']' /></br>" .
"<input type='text' name='last_name' value='$row[\'last_name\']' /></br>" .
"<input type='text' name='teacher' value='$teacherinfo' /></br>"
}
?>
<input type="submit" value="Submit Vote" class="inputbutton"/></br></br></br>
</form>
WHILE I left because I do not know if your query can return more than one record, despite appearing to be a key. If you do not need to check the response of the Ragnar.

If content exists in database, provide form to update it - else provide form to add new row

It's all going wrong. I need to output a form onto my website that will do 1 of 2 things:
If the user already has content in the database, provide a form that posts to self to update the existing content.
If the user does not have content in the database, provide a form to let the user add information to the database.
The forms should submit to themselves to keep coding tidy. I'm getting into a right mess. I'll show what I have so far, but I'm getting in a muddle.
//look in db to see if content exists, if it does set variable
$result = mysql_query(
"SELECT * from tbl_profiles
WHERE user_id = $who
");
while($row = mysql_fetch_array($result))
{
$profileText = $row['text'];
}
// Check if user has content in db
$result = mysql_query(
"SELECT * FROM tbl_profiles WHERE user_id='$who'");
if(mysql_fetch_array($result) !== false){
echo
'<form action="../edit/indexUpdate.php" method="post" name="edit">
Comments:<br />
<textarea name="updatedText" id="comments">' .
$profileText .'
</textarea><br />
<input type="submit" value="Submit" />
</form>'
;}
else{
$profileText = $row['text'];
echo
"<form action='../edit/index.php' method='post' name='add'>
Comments:<br />
<textarea name='comments' id='comments'>" .
$profileText
."</textarea><br />
<input type='submit' value='Submit' />
</form>"
;}?>
You've pretty much got the functionality there, just needs tidying up.
Try something like this:
<?php
//look in db to see if content exists, if it does set variable
$profileText="";
if($result = mysql_query("SELECT * from tbl_profiles WHERE user_id = $who")) {
while($row = mysql_fetch_array($result))
{
$profileText .= $row['text'];
}
?>
<form action="../edit/indexUpdate.php" method="post" name="edit">
Comments:<br />
<textarea name="updatedText" id="comments">
<?php echo $profileText; ?>
</textarea><br />
<input type="submit" value="Submit" />
</form>
<?php
} else {
?>
<form action='../edit/index.php' method='post' name='add'>
Comments:<br />
<textarea name='comments' id='comments'>
<?php echo $profileText; ?>
</textarea><br />
<input type='submit' value='Submit' />
</form>
<?php
}
?>
The basic idea is to add a record if new and update if not. What you can do is use an id to represent the record or -1 if it's a new entry
Something along the lines of:
//Defaults
$recordid=-1;
$name='';
$comments='';
//look in db to see if content exists, if it does set variable
$result = mysql_query(
"SELECT * from tbl_profiles
WHERE user_id = $who
");
// Check if user has content in db
$result = mysql_query(
"SELECT * FROM tbl_profiles WHERE user_id='$who'");
if(mysql_fetch_array($result) !== false){
//Yes. Get the id
$recordid = $result->id;
//Get the values
$name= $result->name;
$comments= $result->name;
}
<form action="../edit/index.php" method="post" name="formdata">
<input type="hidden" name="recordid" value="<? echo htmlspecialchars($recordid) ?>">
<input type="hidden" name="name" value="<? echo htmlspecialchars($name) ?>">
<textarea name="comments" id="comments"><? echo htmlspecialchars($comments) ?></textarea>
<input type="submit" value="submit"/>
</form>
This way a new form will have a -1 but an existing will have an id.
As an additional point it is very important to sanitize your inputs for SQL and what you output in HTML to stop SQL Injections. For your reference on this:
SQL
Little Bobby Tables
Cross Site Scripting

Categories