Get Radio Group Value - php

I am developing a page for multiple choice questions. User is only able to select an answer for each question. I can't seem to retrieve the value (1 indicates correct answer) of the radio buttons.
Here is structure of two tables that I use
CREATE TABLE IF NOT EXISTS `question` (
`q_id` int(10) NOT NULL AUTO_INCREMENT,
`q_qstn_no` int(11) NOT NULL,
`q_text` varchar(300) NOT NULL,
`q_chpt` int(11) NOT NULL,
PRIMARY KEY (`q_id`)
)
CREATE TABLE IF NOT EXISTS `answer` (
`a_id` int(6) NOT NULL AUTO_INCREMENT,
`q_id` int(10) NOT NULL,
`a_text` varchar(255) NOT NULL,
`a_value` tinyint(1) NOT NULL,
PRIMARY KEY (`a_id`)
)
HTML form containing the radio group.
<?php
ini_set('display_errors',1);
error_reporting(E_ALL ^ E_NOTICE);
session_start();
if(isset($_SESSION['tf1_sid']))
{
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form id="form1" name="form1" method="post" action="ques_page_calc1.php">
<p>Questions</p>
<table width="900" border="0" cellpadding="4">
<?php
// db connect
include("dbconn.php");
// db query for questions
$sql_q = "SELECT q_id, q_qstn_no, q_text FROM question";
$query_q = mysql_query($sql_q) or die("MySQL Error: " . mysql_error());
// start loop for questions
$rad2 = 0;
while($data_q = mysql_fetch_array($query_q, MYSQL_ASSOC)){
// echo "<pre>";
// print_r($data_q);
// echo "</pre>";
//
echo "<tr><td width='25' align='center' valign='top'><label><input name='q_no' size='1' type='hidden' value=". $data_q['q_qstn_no'] .">". $data_q['q_qstn_no'] ."</label></td>";
echo "<td>". $data_q['q_text'] ."<br />";
// db query for answers
$sql_a = "SELECT a_id, a_text, a_value FROM answer WHERE q_id=".$data_q['q_id'];
$query_a = mysql_query($sql_a) or die("MySQL Error: " . mysql_error());
//$rad = 0;
// start loop for answers
while($data_a = mysql_fetch_array($query_a, MYSQL_ASSOC)){
echo "<br /><table width='750' border='0'>";
echo "<tr><td><label><input name='answer_".$rad2."' type='radio' value=". $data_a['a_value'] .">". $data_a['a_text'] . "</label></td></tr>";
echo "</table>";
//$rad++;
}
echo "</tr>";
$rad2++;
}
echo "<tr><td><input name='Submit' type='submit' onClick='ques_page_calc1.php' value='Submit'></td></tr>";
mysql_free_result($query_q);
mysql_free_result($query_a);
include("dbconn.php");
?>
</table>
</form>
</body>
</html>
<?php
}
else
{
header("Location:s_login.php");
}
?>
The PHP file to get the value selected
<?php
ini_set('display_errors',1);
error_reporting(E_ALL ^ E_NOTICE);
// include db connection file
include("dbconn.php");
session_start();
if(isset($_POST['Submit']))
{
$id = $_SESSION['tf1_sid'];
echo $id;
$correct = 0;
$ev_id = 1;
//db query to obtain i_id
$sql_i = "SELECT i_id FROM ins_stud WHERE s_id = '$id'";
$query_i = mysql_query($sql_i) or die("MySQL Error: " . mysql_error());
$data_i = mysql_fetch_array($query_i, MYSQL_ASSOC);
print_r($data_i);
// capture values from HTML form
if(!empty($_POST['answer_'.$rad2]))
{
foreach(($_POST['answer_'.$rad2]) as $ans)
{
echo $ans;
var_dump($_POST);
if($ans == 1)
$correct = $correct + 1;
}
//echo $correct;
// insert answer to table
//$sql_eval = "INSERT INTO eval_set (ev_id, q_id, response, created) VALUES ('" . $ev_id . "', '" . $ques_no . "', '" . $ans . "', CURDATE())";
//mysql_query($sql_eval) or die ("Error: " . mysql_error());
//}
}
//
// insert result to table
//$sql_result = "INSERT INTO result (r_score, ev_id, s_id, i_id) VALUES ('" . $correct . "', '" . $ev_id . "', '" . $id . "', '" . $data_i . "')";
//mysql_query($sql_result) or die ("Error: " . mysql_error());
//echo "Result: " . $correct . " questions correct.";
//header("Location:ass_result.php");
}
// close db connection
mysql_close($dbconn);
?>
I thought it was the $_POST['answer_'.$rad2] that was causing the problem since I wasn't sure how to concatenate variables to name field. But now that's changed, there is still no output beyond print_r($data_i); line in the PHP file.

You don't need to give your radio group buttons different names. All of your choices will have a single name (say 'answer') and your PHP script will simply check for
$_POST['answer']
this will give you the selected radio button's value. So however many radio buttons you have for a certain question, give all of them the same name and you're fine. This will also make sure that only one of the radio buttons related to each other can be checked.

I solved it :) I took away the if(!empty...) and replaced it with these.
for($i=1;$i<=$qno;$i++){
$repStr = str_replace("1", $i, "answer_1");
//echo "Question ". $i .": ". $repStr;
$ans = $_POST[$repStr];
//echo "". $radio ."<br>";
if($ans == 1)
$correct = $correct + 1;
// everything before is FIXED :D
// insert answer to table
$sql_eval = "INSERT INTO eval_set (ev_id, q_id, response, created) VALUES ('MAX(ev_id)+1 ', '" . $i . "', '" . $ans . "', CURDATE())";
mysql_query($sql_eval) or die ("Error: " . mysql_error());
}

Related

HTML Dropdown will not generate selected MySQL Tables

I am trying to use this form to display tables in my database. I am unsure what I am doing wrong. I swapped the positions of the "form" and "select" tags assuming that was the fix. But everytime anything from the drop-down is selected the page simple reloads with my normal database creation.
As you can see I am populating my tables within php, my only issue is when I try and put that information into an HTML form it doesn't work. I can send you examples of what I mean it this will help, but I assume you get what I am trying to do.
<!-- Use JavaScript to automatically submit the selection -->
<select name="lstDisplay" onchange="this.form.submit()">
<option value="null">Select an item</option>
<option value="concert">Concert</option>
<option value="attendee">Atendee</option>
<option value="venue">Venue</option>
</select>
<!-- set up alternative button in case JavaScript is not active -->
<noscript>
<input type="submit" name="btnSubmit" value="View the list" />
<br /><br />
</noscript>
<!-- Use a hidden field to tell server if return visitor -->
<input type="hidden" name="hidIsReturning" value="true" />
</form>
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Start with a new database to start primary keys at 1
$sql = "DROP DATABASE " . DATABASE_NAME;
runQuery($sql, "DROP " . DATABASE_NAME, true);
// Create database if it doesn't exist
$sql = "CREATE DATABASE IF NOT EXISTS " . DATABASE_NAME;
//if ($conn->query($sql) === TRUE) {
// echo "The database " . DATABASE_NAME . " exists or was created succesffuly!<br/>";
//}
//else {
// echo "Error creating database " . DATABASE_NAME . ": " . $conn->error;
// echo "<br/>";
//}
runQuery($sql, "Creating " . DATABASE_NAME, false);
// Select the database
$conn->select_db(DATABASE_NAME);
/*
--------------------------
* Create the tables
--------------------------
*/
// Create Table: volunteer
/*
--------------------------
* Create the tables
--------------------------
*/
// Create Table: attendee
$sql = "CREATE TABLE IF NOT EXISTS attendee (
attendee_id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
fName VARCHAR(20),
lName VARCHAR(20),
phone VARCHAR(15),
email VARCHAR(50)
)";
runQuery($sql, "Table:attendee", false);
// Create Table: concert
$sql = "CREATE TABLE IF NOT EXISTS concert (
concert_id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
concert VARCHAR(20) NOT NULL
)";
runQuery($sql, "Table:concert", false);
// Create Table: attendee_concert
$sql = "CREATE TABLE IF NOT EXISTS attendee_concert (
attendee_concert_id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
attendee_id INT(6) UNSIGNED,
concert_id INT(6) UNSIGNED,
paid TINYINT(1)
)";
runQuery($sql, "Table:attendee_concert", false);
// Create Table: venue
$sql = "CREATE TABLE IF NOT EXISTS venue (
venue_id INT(4) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
venueName VARCHAR(25)
)";
runQuery($sql, "Table:venue", false);
/*
--------------------------------------------
* Populate Tables Using Sample Data attendee
* This data will later be collected using a form.
--------------------------------------------
*/
// Populate table: attendee
$attendeeArray = array(
array("Rob", "Nelson", "651-333-3030", "Rob#gmail.com"),
array("Matt", "Doe", "888-867-5309", "Matt#gmail.com"),
array("Tom", "Reynolds", "651-303-9090", "Tom#gmail.com"),
array("Jane", "Doe", "651-678-8901", "Jane#gmail.com"),
array("Emily", "Nelson", "612-234-5678", "Emily#gmail.com"),
array("Timmy", "Turner", "987-098-0987", "Timmy#gmail.com")
);
foreach($attendeeArray as $attendee) {
echo $attendee[0] . " " . $attendee[1] . "<br/>";
$sql = "INSERT INTO attendee (fName, lName, phone, email) "
. "VALUES ('" . $attendee[0] . "', '"
. $attendee[1] . "', '"
. $attendee[2] . "', '"
. $attendee[3] . "')";
runQuery($sql, "Record inserted for: " . $attendee[0], false);
}
// Populate Table: concert
$concertArray = array("Brand New", "Thrice", "Daft Punk", "Kanye West",);
foreach($concertArray as $concert) {
$sql = "INSERT INTO concert (concert) " . "VALUES ('" . $concert . "')";
runQuery($sql, "New record insert $concert[0]", false);
}
// Populate Table: attendee_concert
$attendee_concertArray = array(
array(1,1,1),
array(2,2,1),
array(3,3,1),
array(4,3,1),
array(5,3,1),
array(6,4,1)
);
foreach ($attendee_concertArray as $attendee_concert) {
$sql = "INSERT INTO attendee_concert (attendee_id, concert_id, paid) "
. "VALUES ('" . $attendee_concert[0] . "', '"
. $attendee_concert[1] . "', '"
. $attendee_concert[2] . "')";
runQuery($sql, "New record insert $attendee_concert[0]", false);
}
// Populate Table: venue
$venueArray = array("The Myth", "Target Field", "The Cabooze", "Blue Door Pub");
foreach ($venueArray as $venue) {
$sql = "INSERT INTO venue (venueName) "
. "VALUES ('" . $venue . "')";
runQuery($sql, "New record insert $venue[0]", true);
}
$sql = "SELECT * FROM attendee";
$result = $conn->query($sql);
displayResult($result, $sql);
$conn->close();
function runQuery($sql, $msg, $echoSuccess) {
global $conn;
// run the query
if ($conn->query($sql) === TRUE) {
if($echoSuccess) {
echo $msg . " successful.<br/>";
}
} else {
echo "<strong>Error when: " . $msg . "</strong> using SQL: " . $sql . "<br/>" . $conn->error;
}
} // end of runQuery()
function displayResult($result, $sql) {
if ($result->num_rows > 0) {
echo "<table border='1'>\n";
// print headings (field names)
$heading = $result->fetch_assoc( );
echo "<tr>\n";
// Print field names as table headings
foreach($heading as $key=>$value){
echo "<th>" . $key . "</th>\n";
}
echo "</tr>";
// Print the values for the first row
echo "<tr>";
foreach($heading as $key=>$value){
echo "<td>" . $value . "</td>\n";
}
// Output each record
while($row = $result->fetch_assoc()) {
//print_r($row);
//echo "<br />";
echo "<tr>\n";
// print data
foreach($row as $key=>$value) {
echo "<td>" . $value . "</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
// No results
} else {
echo "<strong>zero results using SQL: </strong>" . $sql;
}
} // end of displayResult( )
?>
Your <select> has onchange="this.form.submit()", which tells JavaScript to submit the form whenever you make a selection. Simply remove this to prevent your form from automatically submitting. Also, you'll want your submission button to be outside of your <noscript> (which really isn't necessary at all).
Ultimately, you want your <form> to look like the following:
<form>
<select name="lstDisplay">
<option value="null">Select an item</option>
<option value="concert">Concert</option>
<option value="attendee">Atendee</option>
<option value="venue">Venue</option>
</select>
<input type="submit" name="btnSubmit" value="View the list" />
<!-- Use a hidden field to tell server if return visitor -->
<input type="hidden" name="hidIsReturning" value="true" />
</form>
Assuming you want to POST data automatically to your server without any sort of user interaction, you should make use of AJAX instead of a form.

MySQL Database not Updating when Form Submitted using PHP

This is a webpage that I have:
// Info to connect to the Wishlist database
$servername = "em";
$dbusername = "";
$password = "!19";
$dbname = "";
// To connect to the database please
$conn = new mysqli($servername, $dbusername, $password, $dbname);
// If unable to connect to the database display this error
if ($conn->connect_error) {
echo "Connection to wishlist failed";
die("Connection failed: " . $conn->connect_error);
}
echo "Once you have added creatures to your wishlist, click " .
"<strong><a href='http://eggcavity.com/edit-wishlist'>here</a></strong> to edit your wishlist.";
// Get current user's username
$current_user = wp_get_current_user();
$username = $current_user->user_login;
// Retrieve data from the database
$sql = "SELECT Name, Stage1 FROM Creatures";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// Display all of the data from the database
echo '<form method="POST">';
while($row = $result->fetch_assoc()) {
echo '<div style="display: inline-block; width: 30%;">' .
'<img src="' . $row["Stage1"] . '"><br>'.
$row["Name"] .
'<br><input type="checkbox" name="creautres[]" value="' .
$row["Name"] .
'"></div>';
}
echo '<br><br><input type="submit" value="Submit"></form>';
} else {
echo "Creatures not found";
}
if(isset($_POST['submit'])){
foreach($_POST['creatures'] as $selected){
$sql = "INSERT INTO " . $username .
" (Creature, Picture, Stage, Gender, Frozen, Notes) VALUES ('" .
$selected . "', 'http://static.eggcave.com/90x90/" . $selected .
"_1', 'Stage1', 'Unspecified', 'Unspecified', 'Unspecified', '')";
if ($conn->query($sql) === FALSE) {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
// Close the connection to the database
$conn->close();
It displays like I want it to:
But it doesn't update the database when I click the submit button.
I've tried echoing $stmt, it seemed to be written as it should be.
When I try echoing $selected, within the loop it doesn't seem to output anything.
Can you help me?
I have updated the code to use one database. Please help me. It still isn't adding.
You had a typo in your checkbox name. I re-did the submit line in the form and the isset() I believe.
The below includes activating error reporting, a try/catch, binding for safety against sql injection. The data saves. You will need to deal with what should be unique data getting saved more than once of course. For instance, a unique key on (Creature,Username). And I would re-think the columns for Id's, but this was your table design. Thanks for allowing us to show you a re-use of a table. Good luck.
schema (from you):
drop table if exists Wishlists;
CREATE TABLE `Wishlists` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Creature` varchar(100) DEFAULT NULL,
`Picture` varchar(200) DEFAULT NULL,
`Stage` varchar(100) DEFAULT NULL,
`Gender` varchar(100) DEFAULT NULL,
`Frozen` varchar(100) DEFAULT NULL,
`Notes` varchar(500) DEFAULT NULL,
`Username` varchar(100) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB; -- <------------------------ went with InnoDB
-- truncate table Wishlists; -- used during early testing
PHP (eggs01.php):
// Info to connect to the Wishlist database
$servername = "serve it up";
$dbusername = "dbu dbu dbu";
$password = "OpenSesame";
$dbname = "my db name";
try {
// To connect to the database please
$conn = new mysqli($servername, $dbusername, $password, $dbname);
if ($conn->connect_error) {
die('Connect Error (' . $conn->connect_errno . ') '
. $conn->connect_error);
}
echo "I am connected and feel happy.<br/>";
if(isset($_POST['submit'])){
// Postback - submit
// Get current user's username
//$current_user = wp_get_current_user(); // remmed out, I don't have your system
//$username = $current_user->user_login; // remmed out, I don't have your system
$theCount=0;
foreach($_POST['creatures'] as $selected){
$Creature=$selected;
$Picture="http://static.eggcave.com/90x90/" . $selected . "_1";
$Stage="Stage1";
$Gender="Unspecified";
$Frozen="Unspecified";
$Notes="Unspecified";
$Username="Stackoverflow123";
$sql = "INSERT Wishlists (Creature, Picture, Stage, Gender, Frozen, Notes, Username) " .
" VALUES (?,?,?,?,?,?,?)";
$stmt = $conn->prepare($sql); // SQL Injection - safe prepare / bind / execute
// 7 s's means 7 strings:
$stmt->bind_param('sssssss', $Creature, $Picture, $Stage, $Gender, $Frozen, $Notes, $Username);
$stmt->execute();
$theCount++;
}
echo "<br>Santa has been notified, count = ".$theCount."<br>";
}
else {
// Just display the form
// Retrieve data from the database
$result = $conn->query("SELECT Name, Stage1 FROM Creatures");
if ($result->num_rows > 0) {
// Display all of the data from the database
echo '<form method="POST">';
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
echo '<div style="display: inline-block; width: 30%;">' .
'<img src="' . $row["Stage1"] . '"><br>'.
$row["Name"] .
'<br><input type="checkbox" name="creatures[]" value="' .
$row["Name"] .
'"></div>';
}
echo '<br><br><button type="submit" name="submit">Submit</button></form>';
$result->close();
} else {
echo "Creatures not found";
}
}
} catch (mysqli_sql_exception $e) {
throw $e;
}
After the submit having selected 3 eggs:
Database Image:
First of all, look at code
$dbname1 = *****";
Here you are missing " :
So replace this with
$dbname1 = "*****";
and try again
First issue is you should never run a SQL statement in a Loop ALWAYS AVOID THIS - as it will put your server through a lot of strain.
And 2nd try this and tell me the out put
foreach($_POST['creatures'] as $selected){
$stmt = "INSERT INTO " . $username . " (Creature, Picture, Stage, Gender, Frozen, Notes) VALUES ('" . $selected . "', 'http://static.eggcave.com/90x90/" . $selected . "_1', 'Stage1', 'Unspecified', 'Unspecified', 'Unspecified', '')";
if ($conn->query($stmt) === TRUE) {
}
}
TO
foreach($_POST['creatures'] as $selected){
$stmt = "INSERT INTO " . $username . " (Creature, Picture, Stage, Gender, Frozen, Notes) VALUES ('" . $selected . "', 'http://static.eggcave.com/90x90/" . $selected . "_1', 'Stage1', 'Unspecified', 'Unspecified', 'Unspecified', '')";
$result = $conn->query($stmt) OR die(var_dump($conn));
var_dump($result->fetch_array(MYSQLI_ASSOC));
die;
}

Possible To Use Insert Query In Fetch Array

I am not sure why this hasn't been answered yet will not that I know of, I am wondering if it's possible to add a insert query with in a while loop I have tried,
but it keeps inserting the comment more then it should (say if it finds 4 status updates it will post the comment in the database 4 times)
I know I have the insert query twice this is not the problem as I had the query where it submits a comment to the database the current query is there for testing purposes.
<?php
require_once ("core/connection.php");
require_once ("core/group_functions.php");
//We need to post the message update in to the database
if(isset($mybb->input['post_message_submit'])) {
$post_message_submit = $mybb->input['post_message_submit'];
$post_message = $mybb->input['post_message'];
$comment_post = $mybb->input['comment_post'];
if(($post_message_submit) && ($post_message)) {
$insert_query = $db->query("INSERT INTO " . TABLE_PREFIX . "groups_posts" . "(posted_by, group_name, post_body)
VALUES ('$mybb_username', '$get_group_url' ,'$post_message')");
} else {
echo "<text style='color:red;'> You Must Specify A Message</a></text>";
}
}
echo "
<form action='' method='POST'>
<textarea name='post_message' id='post_message' placeholder='Whats Going On?'></textarea><br>
<input type='submit' name='post_message_submit' value='Post'>
</form>
";
$fetch_index_query = $db->query("SELECT post_id,posted_by,post_body,post_active,group_name FROM " . TABLE_PREFIX . "groups_posts WHERE group_name='$get_group_url'");
while($fetch_index_groups_array = $db->fetch_array($fetch_index_query)) {
$post_id_row = $fetch_index_groups_array['post_id'];
$posted_by = $fetch_index_groups_array['posted_by'];
$g_name = $_fetch_index_groups_array['g_name'];
$g_body = $fetch_index_groups_array['post_body'];
echo"<br>" . "<a href=''> $posted_by </a>" . "<br>" . $gname
. "<br>____________";
$fetch_comments_query = $db->query("SELECT g_name,post_body,comment_by FROM spud_groups_comments WHERE post_id='$post_id_row'");
while($fetch_groups_comments = $db->fetch_array($fetch_comments_query)) {
$post_body = $fetch_groups_comments['post_body'];
echo ("<br>" . $post_body);
}
$insert_query2 = $db->query("INSERT INTO " . TABLE_PREFIX . "groups_comments" . "(comment_by, post_id, post_body)
VALUES ('$mybb_username', '$post_id_row' ,'$comment_post')");
echo "<br>
<form action='' method='POST'>
<input type='text' name='comment_post' placeholder='Comment then Hit Enter'>
</form>
";
}
//We have done everything we need to do we can now exit and not execute anything beyond this point
exit();
?>
Try to instantiate other $DB object for the insert query. i.e. do not use the same one you are using to fetch the array, as the next use will overwrite the result of the first query that you are looping through.

Retrieve Value from Multiple Looped Textarea

I've built a form for a short-answer quiz. Each question has multiple textboxes for answer (corresponding to instruction in the question i.e. list two components, three advantages, etc.). I've designed the form as such so that the answers can be evaluated independently against a set of answers. Each question can have many answer suggestions. Here is the 'answer' table structure:
CREATE TABLE IF NOT EXISTS `answer` (
`a_id` int(10) NOT NULL AUTO_INCREMENT,
`q_id` int(10) NOT NULL,
`a_text` text NOT NULL,
`a_keyword` text NOT NULL,
PRIMARY KEY (`a_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=15 ;
This is the code of the form:
<?php
session_start();
if(isset($_SESSION['tf1_sid'])){
?>
<head>
<title>Dahlia | Formative Assessment</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" name="form1" method="post" action="s_ass_result_new.php">
<h2>Short-answer Questions</h2>
<table width="590" border="0" cellpadding="2" align="center">
<?php
// db connect
include("dbconn.php");
// db query for questions
$sql_q = "SELECT q_id, q_no, q_text, q_field FROM question";
$query_q = mysql_query($sql_q) or die("MySQL Error: " . mysql_error());
// start loop for questions
//$rad = 1;
while($data_q = mysql_fetch_array($query_q, MYSQL_ASSOC)){
$qfield = $data_q['q_field'];
$qno = $data_q['q_no'];
echo "<tr><td width='20' align='center' valign='top'><label><br /><input name='q_no' size='1' type='hidden' value=". $data_q['q_no'] .">". $data_q['q_no'] ."</label></td>";
echo "<td><br />". $data_q['q_text'] ." (<a href='s_help.php?s_id=". $_SESSION['tf1_sid'] ."&q_id=". $data_q['q_id'] ."' target='_blank'>Help</a>)</td>";
for($rad=1;$rad<=$qfield;$rad++){
echo "<tr><td></td><td><textarea name='answer_".$rad."' cols='55' rows='2' id='textarea1'></textarea></td></tr>";
echo "<script>document.getElementById('textarea1').focus()</script>";
//$rad++;
}
}
echo "<tr></tr><tr><td></td><td><input name='Submit' type='submit' value='Submit' onClick='return confirm(\"Are you sure?\")'></td></tr>";
mysql_free_result($query_q);
include("dbconn.php");
?>
</table>
</form>
</body>
</html>
<?php
}
else
{
header("Location:s_login.php");
}
?>
The form is displaying fine but I'm having trouble retrieving values being submitted through the text area. Below is the code to retrieve those values:
<?php
// include db connection file
include("dbconn.php");
session_start();
if(isset($_POST['Submit']))
{
$id = $_SESSION['tf1_sid'];
$qno = $_POST['q_no'];
$ansspc = $_POST['q_field'];
?>
<head>
<title>Dahlia | Formative Assessment</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h2>Answer Review</h2>
<table width="590" border="0" cellpadding="2" align="center">
<?php
//db query to obtain i_id - to insert to RESULT table
$sql_i = "SELECT i_id FROM ins_stud WHERE s_id = '$id'";
$query_i = mysql_query($sql_i) or die("MySQL Error: " . mysql_error());
$data_i = mysql_fetch_assoc($query_i);
$ins_id = $data_i['i_id'];
//$j = 1;
$arr_ind = 1;
$atext = array(1);
$ans = array(1);
//FOR LOOP TO RETRIEVE VALUES FROM TEXT AREA
for($i=1;$i<=$q_no;$i++){
for($k=1;$k<=$ansspc;$k++){
$repStr = str_replace("1", $k, "answer_1");
echo "Question ". $i .": Answer: ". $repStr;
$ans[] = $_POST[$repStr];
echo $ans;
}
$sql_check = "SELECT a_text FROM answer WHERE q_id='$i'";
$query_ch = mysql_query($sql_check) or die("MySQL Error: " . mysql_error());
$data_ch = mysql_fetch_assoc($query_ch);
$atext[] = $data_ch['q_ans'];
//$j++;
}
...
It was working previously when I had the questions set with one text area each. What I intend to do is have each answer to be compared with each answer suggestion.
Example:
State two advantages of...
Two text area: ans1, ans2
Four suggested answers: soln1, soln2, soln3, soln4
So I'd compare ans1 with soln1, soln2, soln3, soln4 then the same goes for the ans2.
Edited:
//start loop for questions & answers
while($data_q = mysql_fetch_array($query_q, MYSQL_ASSOC)){
//process returned data
foreach ($_POST['answer'] as $questionNumber => $answerList){
echo "question " . $questionNumber . ": \n";
foreach ($answerList as $key => $answer){
$ans[] = $answer;
echo "answer " . $key . ": " . $answer . "\n";
}//end foreach_in
}//end foreach_out
$jawapan = explode(" ", $ans[$arr_ind]);
$jwpn = trim($jwpn);
foreach($jwpn as $eval){
if (stripos($atext[$arr_ind], $eval) !== false){ //$atext: query for answer suggestions
//answer match with first suggestion
echo "<p align='justify'><img src='image/mark.png' border='0' width='20' height='20'> ". $ans[$arr_ind]. "</p>";
}//if
{else
//answer doesn't match with first suggestion; check next suggestion
for($m=1;$m<=$box;$m++){...}// $box = no. of text area in form
}//else
echo "<p align='justify'><label><b>SUGGESTED ANSWER:</b> <br><input name='answer_".$rad."' type='hidden' value=''>". $atext[$arr_ind] . "</label></p>";
$arr_ind++;
}//foreach
Best is to use arrays in the naming of the textareas
Outputting the textarea (i left out all markup extras just to make it clear)
while ($data_q = mysql_fetch_array($query_q, MYSQL_ASSOC)) {
$qfield = $data_q['q_field'];
$qno = $data_q['q_no'];
for ($rad = 1; $rad <= $qfield; $rad++) {
echo "<textarea name='answer[" . $qno . "][" . $rad . "]' id='textarea_" . $qno . "_" . $rad . "'>";
}
}
and processing the returned data
foreach ($_POST['answer'] as $questionNumber => $answerList) {
echo "question " . $questionNumber . ": \n";
foreach ($answerList as $key => $answer) {
echo "answer " . $key . ": " . $answer . "\n";
}
}

Database query php MySQL - no search results displayed

(PROBLEM IS VERY DETAILED FOR TOO LONG DIDN'T READ: "My guess is that i'm using the MYSQL_FETCH_ARRAY wrong.")
Hello! The following codes purpose is to do a basic search in the database. The data is passed by a form. The tutorial I was using was written by: 'Frost of Slunked.com' and it was a basic register/login php MySQL tutorial, which worked perfectly. I managed to write a woking table-updater function and form-submit to add new data to the selected (so that's working as intended.
config.php - conncets to the MySQL server, selects the database, starts the session, requires the functions.php (with authors comments included)
<?php
/*****************************
File: includes/config.php
Written by: Frost of Slunked.com
Tutorial: User Registration and Login System
******************************/
// start the session before any output.
session_start();
// Set the folder for our includes
$sFolder = '';
/***************
Database Connection
You will need to change the user (user)
and password (password) to what your database information uses.
Same with the database name if you used something else.
****************/
mysql_connect('localhost', 'myusername', 'mypassword') or trigger_error("Unable to connect to the database: " . mysql_error());
mysql_select_db('tormex') or trigger_error("Unable to switch to the database: " . mysql_error());
/***************
password salts are used to ensure a secure password
hash and make your passwords much harder to be broken into
Change these to be whatever you want, just try and limit them to
10-20 characters each to avoid collisions.
****************/
define('SALT1', '24859f##$##$');
define('SALT2', '^&##_-=+Afda$#%');
// require the function file
require_once 'functions.php';
// default the error variable to empty.
$_SESSION['error'] = "";
// declare $sOutput so we do not have to do this on each page.
$sOutput="";
?>
functions.php - has multiple functions (login, createRide, Register etc.). Most of the functions purpose is to get the values from the submitted HTML forms and then maintain the required actions - I will only mentioned my searchRide function (which in my guess has the error or atleast, has to do something with it) and the createRide function, which is working properly.
<?php ...
unction searchRide($pWhen_min, $pWhen_max, $pFrom, $pTo){
if (!empty($pWhen_min) && !empty($pWhen_max) && !empty($pFrom) && !empty($pTo)) {
global $sql2, $query2;
$sql2 = "SELECT * FROM ride WHERE `from` ='$pFrom' AND `to` = '$pTo' AND `when` >= '$pWhen_min' AND `when` <= '$pWhen_max' ";
$query2 = mysql_query($sql2) or trigger_error("Query Failed: " . mysql_error());
}
}
function createRide($pFrom, $pTo, $pWhen, $pSeats, $pPrice, $pCar){
if (!empty($pFrom) && !empty($pTo) && !empty($pWhen) && !empty($pSeats) && !empty($pPrice) && !empty($pCar)){
$sql = "SELECT id FROM users WHERE username= '" . $username . "' LIMIT 1";
$result = mysql_query($sql);
if(!$result) {
trigger_error("ELKURTAD " . mysql_error());
}
$row = mysql_fetch_array($result);
$sql = "INSERT INTO ride (`from`, `to`, `when`, `seats`, `price`, `car`, `u_id`)
VALUES ('" . $pFrom . "', '" . $pTo . "', '" . $pWhen . "',
'" . $pSeats . "', '" . $pPrice . "', '" . $pCar . "', '" . $result . "');";
$query = mysql_query($sql) or trigger_error("Query Failed: " . mysql_error());
if ($query) {
return TRUE;
}
}
return FALSE;
}
...?>
searchRide.php - checks if the variables which are dedicated to get the search filter values have any values; (in the else statement) if there are no values, the form wasn't submitted and displays the searchRide form and after result passes the variables for the searchRide.php ( $_SERVER['PHP_SELF'] )
<?php
require_once 'config.php';
$sOutput .= '<div id="searchRide-body">';
if (isset($_GET['action'])) {
switch (strtolower($_GET['action'])) {
case 'searchride':
if (isset($_POST['when_min']) && isset($_POST['when_max']) && isset($_POST['from']) && isset($_POST['to'])) {
if (searchRide($_POST['when_min'], $_POST['when_max'], $_POST['from'], $_POST['to'])) {
while($row = mysql_fetch_array($query2)){
$sOutput .= "' ID: '" .$row['id'] . "' <br />
When: '" . $row['when'] . "' <br />
From: '" . $row['from'] . "' <br />
To: '" . $row['to'] . "' <br />
Seats left: '" . $row['seats'];
}
}
}
}
}else{
if (isset($_SESSION['error'])) {
$sError = '<span id="error">' . $_SESSION['error'] . '</span><br />';
}
$sOutput .= '<h2>Search for rides</h2>
' . $sError . '
<form name="searchride" method="post" action="' . $_SERVER['PHP_SELF'] . '?action=searchride">
From: <input type="text" name="from" value=* /><br />
To: <input type="text" name="to" value=* />
When_min: <input type="text" name="when_min" value=* />
When_max: <input type="text" name="when_max" value=* />
<br /><br />
<input type="submit" name="submit" value="Search" />
</form>
<br />
<h4>Would you like to Go back?</h4>';
}
echo $sOutput . "<br />";
echo "TEST string" . "<br />";
echo $query2 . " query2<br /> ";
echo $sql2 . " sql2<br />";
echo $row . "<br />";
?>
At the end of this code You can see some printed variables, which are used to check their values after searRide form is submitted.
I updated my database with the following data and checked with phpMyAdmin for the exact values so I can test the search with existing data:
From: TEST01
To: TEST02
When: 500
Seats: 5
Price: 7
Car: volvo
Test data submitted with the searchRide form:
From: TEST01
To: Test02
When_min: 1
Whn_max: 3000
After is press Search button on the searchRide form these are the following results (what the browser shows):
(sOutput variable
TEST WRITE TEXT
Resource id #5 (query2 variable
SELECT * FROM ride WHERE from ='TEST01' AND to = 'TEST02' AND when >= '1' AND when <= '5000' (sql2 variable
(row variable
After this I inserted the SQL query in the phpMyAdmin SQL command line and resulted the data I was searching for.
Was trying many times to figure out what could be the problem, with my own knowledge and varius searches on google, php.net and w3chools.com.
My guess is that i'm using the MYSQL_FETCH_ARRAY wrong.
following condition will not work
if (searchRide($_POST['when_min'], $_POST['when_max'], $_POST['from'], $_POST['to'])) {
as you have not return any value from searchRide function you need to return true to go into the condition.

Categories