HTML Dropdown will not generate selected MySQL Tables - php

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.

Related

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;
}

Checking Table exists before inserting php sql

I am trying to check if a table exists before entering the data into it. I am trying mysql_query and getting errors that I should be using mysqli, but it does not seem to be working for me.
This is my code so far:
$AllData = $_POST["table"];
foreach ($AllData as $sigleData) {
$table = $sigleData['name'];
$columns = implode(", ", $sigleData['columns']);
$columnData = implode(" ',' ", $sigleData['data']);
// Insert into database tuple data
$sqlQuery = "INSERT INTO " . $table . " ( " . $columns . ") VALUES( '" . $columnData . "')";
if ($dbConnectionT->query($sqlQuery) == TRUE) {
echo "database updated";
echo "</br>";
}
}
Try this way to check table exists or not using this custom function and then insert row to your db.
function check_table_exist($table){
global $dbConnection; // see here global connection variable
$sql = "SHOW tables LIKE '".$table."'";
$res = $dbConnection->query($sql);
return ($res->num_rows > 0);
}
#check first table exists or not
if(check_table_exists($table)){
$sqlQuery = "INSERT INTO " . $table . " ( " . $columns . ") VALUES( '" . $columnData . "')";
//do other stuff........
}else{
echo "Table Not Exists";
die('Going Out');
}
Table name is accepted as POST parameter, seriously !! - bad practice.
You can do various check to table existence like
DESC tbl_name;
SHOW CREATE TABLE tbl_name;
SHOW TABLES like 'tbl_name';

Using PHP to add to MySQL adds twice and issue with foreign id constraint

For some reason, when I add to my database, this line
$query = "INSERT INTO customers (id, name, address) VALUES (NULL,'$name', '$address')"; adds the customer twice. So one customer would have both id 1 and id 2. The subsequent getting of $last_id will always get the second id number, so for customer entered with id 1 and 2, $last_id == 2. I'm eliminating the issue by deleting first copy, but how do I keep it from happening in the first place? I'm using Chrome, but it happens in safari as well.
<?php
// Include the ShoppingCart class. Since the session contains a
// ShoppingCard object, this must be done before session_start().
require "../application/cart.php";
session_start();
?>
<!DOCTYPE html>
<?php
$orderErr = $nameErr = $addressErr = "";
$name = $address = "";
// If this session is just beginning, store an empty ShoppingCart in it.
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = new ShoppingCart();
}
if (($_SESSION['cart']->count_order()) == 0) {
$orderErr = "There is nothing in the order, cannot checkout";
}
// sanitizing function
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
}
else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["address"])) {
$addressErr = "Address is required";
}
else {
$address = test_input($_POST["address"]);
}
//if there is an order, and name and address exist after sanaitizing,
// add to db
if ($name != "" && $address != "" && ($_SESSION['cart']->count_order()) != 0) {
require_once 'login.php';
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die($conn->connect_error);
//adding current customer
$query = "INSERT INTO customers (id, name, address) VALUES (NULL, '$name', '$address')";
echo "ok<br>";
$result = $conn->query($query);
if ($conn->query($query) === TRUE) {
echo "New record created successfully" . "<br>";
$last_id = $conn->insert_id;
echo $last_id . "<br>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$delete_id = $last_id - 1;
// deleting duplicate
$query = "DELETE FROM customers WHERE id = '$delete_id'";
if ($conn->query($query) === TRUE) {
echo "duplicate deleted successfully" . "<br>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
//send orders to db
$_SESSION['cart']->send_order_to_db($last_id, $conn);
$conn->close();
session_unset(); // remove all session variables
session_destroy();
}
}
?>
<html lang="en">
<head>
<title>Checkout</title>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<h2>Checkout</h2>
<p>Here is your order: <?php
// Poor man's display of shopping cart
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = new ShoppingCart();
}
$_SESSION['cart']->table();
?></p>
<span class="error"><?php echo $orderErr;?></span>
<h3> Checkout Form: </h3>
<p><span class="error">* required field.</span></p>
<form method = "post" >
Name: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
Address: <input type="text" name="address" value="<?php echo $address;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<p>Your credit card will be billed. Thanks for the order!</p>
<p>Shop some more!</p>
</body>
</html>
The second issue is, the function SOLVE. SEE EDIT BELOW
public function send_order_to_db($last_id, $conn) {
foreach ($this->order as $variety => $quantity)
$query = "INSERT INTO orders (id, variety, quantity) VALUES" .
"('$last_id', '$variety', '$quantity')";
echo 'added ' . $quantity . ' ' . $variety;
$result = $conn->query($query);
if (!$result) echo "INSERT failed: $query<br>" .
$conn->error . "<br><br>";
}
which I call after entering the customer's information, only adds the last element from the array $this->order. Is it because foreach does not work like a loop? So then I'd use a for loop right? Or does this have something to do with the database?
EDIT
I realized I did not have brackets around the foreach statement. Now that I do, it works. Adds all orders and all have the same id.
Here's my database:
/* To start with a fresh new database named store, we will delete one
* if one already exists:
*/
DROP DATABASE IF EXISTS store;
CREATE DATABASE store;
GRANT ALL PRIVILEGES ON store.* to user#localhost IDENTIFIED BY 'name';
USE store;
CREATE TABLE IF NOT EXISTS customers (
id int NOT NULL AUTO_INCREMENT,
name text NOT NULL,
address text NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS orders (
id int NOT NULL,
variety varchar(20) NOT NULL,
quantity int(11) NOT NULL,
PRIMARY KEY (id, variety),
FOREIGN KEY (id)
REFERENCES customers(id)
ON DELETE CASCADE
ON UPDATE CASCADE
) ENGINE=InnoDB;
Problem 1
Your first problem being that the record is inserted twice is because you're running the query twice:
$result = $conn->query($query);
if ($conn->query($query) === TRUE) {
You should use the $result contents to check whether it worked or not instead of re-running the query:
$result = $conn->query($query);
if ($result === true) {
Problem 2
The record only inserts the last record - this is because you aren't using braces for your foreach loop, so it only runs the first line after the control structure in the loop - the rest will only execute once the loop has completed. See commented flow:
public function send_order_to_db($last_id, $conn) {
foreach ($this->order as $variety => $quantity)
// This line is run in the loop
$query = "INSERT INTO orders (id, variety, quantity) VALUES" .
"('$last_id', '$variety', '$quantity')";
// This line is only run once, after the foreach has finished
echo 'added ' . $quantity . ' ' . $variety;
$result = $conn->query($query);
if (!$result)
echo "INSERT failed: $query<br>" .
$conn->error . "<br><br>";
}
You just need to wrap the contents in braces:
public function send_order_to_db($last_id, $conn) {
foreach ($this->order as $variety => $quantity) {
// This line is run in the loop
$query = "INSERT INTO orders (id, variety, quantity) VALUES" .
"('$last_id', '$variety', '$quantity')";
// So is all below now
echo 'added ' . $quantity . ' ' . $variety;
$result = $conn->query($query);
if (!$result) {
echo "INSERT failed: $query<br>" .
$conn->error . "<br><br>";
}
}
}
Note that the braces after the if at the end aren't required, but it's good practice to use braces at all times for readability (and to help you find mistakes like this).

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.

Get Radio Group Value

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());
}

Categories