how to insert selected options into a database - php

I am building a php based quiz for website. I am a beginner. I coded for getting the questions and options from database and display them in the form in my page.when the user selects the option i want the the answers to be inserted to my database.I wrote some bsic code but its not working pls help. Here is my code
The table for question is having 7rows(qid,question,optiona,optionb,optionc,optiond,answeroption),answers table is having simple2rows(qid,answer)
if(isset($_POST['next']))
{
$a=$_POST['a'];
}
if(!isset($a))
{
$a=0;
}
include('connection.php');
mysql_query("INSERT INTO answers (username,qid, option)
VALUES ($username,a-1,'$_POST('option'))");
$sql1="SELECT * FROM exam1 LIMIT 1 OFFSET $a";
$result=mysql_query($sql1);
echo "<form method='post' action='quiz.php'>";
while ($row = mysql_fetch_array($result))
{
echo $row['question']. "<br/>";
echo "<input type='radio' value='optiona' name='option'>" .$row['optiona'];
echo "<input type='radio' value='optionb' name='option'>" .$row['optionb'];
echo "<input type='radio' value='optionc' name='option'>" .$row['optionc'];
echo "<input type='radio' value='optiond' name='option'>" .$row['optiond']; "<br/>";
}
$c=$a-1;
$b=$a+1;
echo "<input type='hidden' value='$c' name='a'>";
echo "<input type='submit' name='previous' value='previous'> ";
echo "<input type='hidden' value='$b' name='a'>";
echo "<input type='submit' name='next' value='next'> ";
echo "<input type='reset' name='reset' value='Reset'>";
echo "</form>";
?>

You need to study up on basic PHP syntax. $_POST is not a function. It's an array. e.g.
$var = $_POST['var'];
^-- ^--- note the bracketing.
Even if the code DID work, you'd be wide open to SQL injection attacks.

Big big atention! I hope this is just an test code note final one!
Your code is Inject Vulnerably here $a=$_POST['a'];
I recomend to replace with this one $a= filter_input(INPUT_POST, 'a', FILTER_SANITIZE_STRING); this is an escaped from attacks!
I hope it hepls you

Related

PHP MySql update query not working,says:- Undefined Index [duplicate]

This question already has answers here:
How to get input field value using PHP
(7 answers)
Closed 6 years ago.
I have follow the tutorial of it where i want to update my database using two php files.
<?php
while($row = mysqli_fetch_array($records))
{
echo "<tr><form action =update.php method=post>";
echo "<td><input type=text name=Cname value='".$row['CustomerName']."'></td>";
echo "<td><input type=number name=size min=1 value='".$row['TableSize']."'></td>";
echo "<td><input type=date name=Adate value='".$row['DateA']."'></td>";
echo "<td><input type=time name=Atime value='".$row['TimeA']."'></td>";
echo "<td><input type=tel name=phonenumber value='".$row['PhoneNumber']."'></td>";
echo "<input type=hidden name=id value='".$row['TableID']."'>";
echo "<td><input type=submit>";
echo"</form></tr>";
}
?>
this is what i use for the first php file
as for the update.php:
<?php
$con = mysqli_connect('127.0.0.1','root','');
mysqli_select_db($con,'restaurant');
$sql = "UPDATE addtable SET CustomerName='$_POST[Cname]', TableSize='$_POST[size]', DateA='$_POST[Adate]',TimeA='$_POST[Atime]',PhoneNumber='$_POST[phonenumber]', WHERE TableID=$_POST[id]";
if(mysqli_query($con,$sql))
header("refresh:1; url=AssignBooking.php");
else
echo "Not Update";
?>
but the $sql line just doesn't work as it says that
Undefined index: Cname and other indexes too.
put quotes outside the post variable:
$sql = "UPDATE addtable SET CustomerName='".$_POST['Cname']."', TableSize='".$_POST['size']."', DateA='".$_POST['Adate']."',TimeA='".$_POST['Atime']."',PhoneNumber='".$_POST['phonenumber']."', WHERE TableID=".$_POST['id'];
According to your code put the name attributes value ' single quote.
<?php
while($row = mysqli_fetch_array($records))
{
echo "<tr><form action =update.php method=post>";
echo "<td><input type=text name='Cname' value='".$row['CustomerName']."'></td>";
echo "<td><input type=number name='size' min=1 value='".$row['TableSize']."'></td>";
echo "<td><input type=date name='Adate' value='".$row['DateA']."'></td>";
echo "<td><input type=time name='Atime' value='".$row['TimeA']."'></td>";
echo "<td><input type=tel name='phonenumber' value='".$row['PhoneNumber']."'></td>";
echo "<input type=hidden name="id" value='".$row['TableID']."'>";
echo "<td><input type=submit>";
echo"</form></tr>";
}
?>
Put quotes accordingly
UPDATE addtable SET CustomerName='".$_POST['Cname']."',TableSize='".$_POST['size']."', DateA='".$_POST['Adate']."',TimeA='".$_POST['Atime']."',PhoneNumber='".$_POST['phonenumber']."' WHERE TableID=$_POST['id'];

How do I autochange the name of radio buttons from while loop? php

Here is the scenario. in my database, I have like 4 questions. each questions have individual 5 radio buttons. I tried to retrieve the information from database. it shows my list of questions and radio buttons individually, but the BIG problem here is they are in the same group. example. in question 1, I picked 1st radio button, then in question 2, I picked the 2nd radio button. in question 1, the radio button I choose disappeared. so basically. the whole loop have single radio button name. how do I fix this dynamically? like auto change of radio-button-name for each question?
<form method='post' action='test.php'>
<?php
include 'db_connect.php';
$query = "SELECT * FROM test";
$result = $conn->query($query);
$num_results = $result->num_rows;
#if ($num_results > 0) {
#}
while ($row = $result->fetch_assoc()) {
extract($row);
echo $row['test1'];
echo "<input type='radio' name='question_button' value='1'>";
echo "<input type='radio' name='question_button' value='2'>";
echo "<input type='radio' name='question_button' value='3'>";
echo "<input type='radio' name='question_button' value='4'>";
echo "<input type='radio' name='question_button' value='5'>";
echo "<br>";
}
$testbutton = isset($_POST['question_button']) ? $_POST['question_button'] : "";
if (isset($_POST['submit'])) {
echo $testbutton;
}
?>
<html>
<input type='submit' name='submit' value='submit'>
</form>
</html>
P.S. Edit. my original intention is to add or get the sum of the radio buttons. what syntax should i use?
to change button name dynamically
change like following
$question=0;
while ($row = $result->fetch_assoc()) {
extract($row);
echo $row['test1'];
$question++;
echo "<input type='radio' name=".$question." value='1'>";
echo "<input type='radio' name=".$question." value='2'>";
echo "<input type='radio' name=".$question." value='3'>";
echo "<input type='radio' name=".$question." value='4'>";
echo "<input type='radio' name=".$question." value='5'>";
echo "<br>";
}
$question is just for example,
you can change redio button name according to your need.
I can't see what your database query is producing, but at a guess, I'd say you should be assigning a radio button id to your question in the database field. Then, when you get the results back, you can assign it with something like:
while ($row = $result->fetch_assoc()) {
extract($row);
echo "<input type='radio' name='".$row['question_name']."' value='".$row[question_id]."'>";
echo "<br>";
}
This should make every radio box unique so long as the data in the database is unique. If this doesn't help, may I see the results of the database query and I can edit my answer.
Simply give the radio button a group name differently as bellow example
// 1. Get the handler for counter.
$counter = 1;
// 2. Iterating through the results.
while ($row = $result->fetch_assoc()) {
$name = "question_" . $counter . "_button";
extract($row);
echo $row['test1'];
echo "<input type='radio' name=$name value='1'>";
echo "<input type='radio' name=$name value='2'>";
echo "<input type='radio' name=$name value='3'>";
echo "<input type='radio' name=$name value='4'>";
echo "<input type='radio' name=$name value='5'>";
// Increment the counter by 1 for each question.
$counter += 1;
}

Multiple echoed delete-edit buttons in PHP event listener

I am trying a trivial PHP assignement. I am running my own SQL server locally and I have created a DB on it called student. This database contains many tables. One of them is called announcement. The fields of this table are id, date, subject, text.
I am asked to display those announcements to a user that has the authority to delete and/or modify those entries of the DB. Each entry needs to be seperated from the next one and each entry has to have it's own Delete and Edit button. New entries can also be added to the database so the # of entries currently on the DB is not known.
So far I have done something like this:
<?php
$db = mysql_connect("localhost", "root", "");
mysql_select_db("student",$db);
mysql_set_charset('utf8',$db);
$result = mysql_query("SELECT * FROM announcement",$db);
$announcementID = 1;
WHILE($myrow = mysql_fetch_array($result))
{
echo "<br><h2>Announcement No".$announcementID."</h2>";
echo "<input type=\"submit\" name=\"Delete\" value=\"Delete\"><input type=\"submit\" name=\"Edit\" value=\"Edit\"><br>";
echo "<br>Date: ".$myrow["date"];
echo "<br>Subject: ".$myrow["subject"];
echo "<br>Text: ".$myrow["text"];
$announcementID=$announcementID+1;
echo '<br><hr />';
}
?>
This is a part of a larger php file that displays a webpage with the entries properly formatted.
Although I do create the separate buttons needed for each distinct announcement I do not think this can work out since I can't create an ActionListener (forgive me but I do not know how this is called in PHP) for those buttons and I am not even sure it is possible considering that all of those buttons will have the same name. Any workaround?
For PHP to be able to indetify that the user has clicked the button, you would need to surround the each row of inputs.
I've improved your code a little, as we need to pass over the ID of the announcement to the delete-record.php script for it to be able to identify which record to delete from the table.
$db = mysql_connect("localhost", "root", "");
mysql_select_db("student",$db);
mysql_set_charset('utf8',$db);
$result = mysql_query("SELECT * FROM announcement",$db);
while($myrow = mysql_fetch_array($result))
{
echo '<form action="delete-record.php" method="POST">';
echo '<input type="hidden" name="id" value="' . $myrow["id"] . '">';
echo "<br><h2>Announcement No".$announcementID."</h2>";
echo "<input type=\"submit\" name=\"delete\" value=\"delete\"><input type=\"submit\" name=\"edit\" value=\"edit\"><br>";
echo "<br>Date: ".$myrow["date"];
echo "<br>Subject: ".$myrow["subject"];
echo "<br>Text: ".$myrow["text"];
echo '<br><hr />';
echo "</form>";
}
And then in the delete-record.php you can go with this:
if(isset($_POST['id'], $_POST['delete'])) {
$announcementid = $_POST['id'];
mysql_query("DELETE FROM announcement WHERE id = $announcementid");
}
For future reference, instead of using $announcementID = $announcementID+1; you can simply use the post-incremental operator $announcementID++;
I also suggest you to read up on MySQLi or PDO's prepared statements to secure yourself against SQL Injections and other SQL vulnerabilities.
Make javascript redirection to delete script.
WHILE($myrow = mysql_fetch_array($result))
{
echo "<br><h2>Announcement No".$announcementID."</h2>";
echo "<input type=\"submit\" name=\"Delete\" value=\"Delete\" onClick=\"window.location='delete_announcement.php?announcemenID=".$announcementID."';\">"
echo "<input type=\"submit\" name=\"Edit\" value=\"Edit\" onClick=\"window.location='edit_announcement.php?announcemenID=".$announcementID."';\"><br>";
echo "<br>Date: ".$myrow["date"];
echo "<br>Subject: ".$myrow["subject"];
echo "<br>Text: ".$myrow["text"];
$announcementID=$announcementID+1;
echo '<br><hr />';
}
And delete_announcement.php connect to the DB and do
mysql_query("DELETE FROM announcement WHERE announcemenID=" . $_REQUEST["announcemenID"],$db);
Don't forget to make sure that $_REQUEST["announcemenID"] only hold integers.
For edit you will need to create separate page edit_announcement.php with all the fields editable.
Create a form around each row with a Delete button
WHILE($myrow = mysql_fetch_array($result))
{
echo "<form method='post' action='delete-record.php'>";
echo "<br><h2>Announcement No".$announcementID."</h2>";
echo "<input type=\"submit\" name=\"Delete\" value=\"Delete\"><input type=\"submit\" name=\"Edit\" value=\"Edit\"><br>";
echo "<br>Date: ".$myrow["date"];
echo "<br>Subject: ".$myrow["subject"];
echo "<br>Text: ".$myrow["text"];
echo "<input type='hidden' name='formID' value='$announcementID' />";
echo "<input type='submit' value='Delete row'/>";
echo "</form>";
echo '<br><hr>';
$announcementID=$announcementID+1;
}
Then in delete-record.php:
<?php
if(isset($_POST['formID'])){
// Delete record query here
}
...

php get value of submit button when value is a variable

I tried to search but was unable to find an answer for this question.
I am trying to get the value of the button in my submit button that is a variable.
CODE is as follows
$penrequest = "select * from request where status='pending';";
$penreg = mysql_query($penrequest);
echo "<form method='post' action=''>";
while ($row = mysql_fetch_array($peneg))
{
echo "<input type='submit' name='answer' value='$appdeny'>";
}
if (isset($_POST['answer']))
{
echo $appdeny;
}
Ok the code works...if you hit the button its caught by the if statement like its supposedt o be. the variable $appdeny is a messageID number filled from a mysql database which can change. When the user clicks a button i want to print the messageID of the number displayed as the value of the answer button.
Change:
echo "<input type='submit' name='answer' value='$appdeny'>";
to:
echo "<input type='submit' name='answer' value='" . $row['appdeny'] . "'>";
Change:
echo $appdeny;
to:
echo $_POST['answer'];
You also need to do:
echo "</form>";
after the while loop.

How to echo out dynamic checkboxes?

I have problems displaying my checkboxes. Can anyone please help? I search the solution online and I tried the codes but it doesn't work.
Here is my codes
<?php
include "mysqli.connect.php";
// Make a MySQL Connection
$retrieveflavor = "SELECT * FROM flavor";
$result = $mysqli->query($retrieveflavor);
while ($row = $result->fetch_array(MYSQLI_ASSOC))
{
//echo "<input type='checkbox' name='candyFlavors[]' value=".$row['flavorname']."/>";
//echo "<input type=\"checkbox\" name=\"candyFlavors[]\" value=\"$row[flavorname]\">";
//echo "<input name=\"candyFlavors[]\" type='checkbox' value='"$row[flavorname]"'/>";
echo "<td><img src=".$row['image']." width='240px' height='190px'></td>";
echo "<input type=\"checkbox\" name=\"candyFlavors[]\" value=\"$row[flavorname]\">";
}
?>
I think it should be like this.
echo "<input type=\"checkbox\" name=\"candyFlavors[]\" value=\"".$row['flavorname']."\">";
You missed single quote in $row[flavorname]
echo '<input type="checkbox" name="candyFlavors[]" value="'.$row['flavorname'].'">';
Try this

Categories