MySQL Database not Updating when Form Submitted using PHP - 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;
}

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.

Display image from MySql database in Php server

I send an image from my Android Application to my Php server using a MySql database, but when i try to display the image in browser it doesn't work.
This is how I send the picture
String imageString=Base64.encodeBytes(this.image);
nameValuePairs.add(new BasicNameValuePair("image", imageString));
And this is how I try to display it
echo '<img src="data:image/jpeg;base64,'.base64_encode( $row['image'] ).'"/>';
I've checked and imageString in my app is different from base64_encode( $row['image']).
MySql part
$conn = new mysqli($server, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to create table
$sql = "CREATE TABLE Posts (
id INTEGER UNSIGNED AUTO_INCREMENT PRIMARY KEY,
user VARCHAR(50) NOT NULL,
date VARCHAR(12) NOT NULL,
event VARCHAR(1000),
image BLOB
)";
if ($conn->query($sql) === TRUE) {
echo "Table Posts created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
$conn->close();
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$user = $_POST['user'];
$date = $_POST['date'];
$event = $_POST['event'];
$image = $_POST['image'];
echo "Test";
$sql = "INSERT INTO Posts (user, date, event,image) ";
$sql .= "VALUES ('$user','$date', '$event', '$image')";
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
} else {
echo "Insert success";
}
mysql_close($con);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["user"]. $row["date"]. $row["event"]. "<br>";
echo '<img src="data:image/jpeg;base64,'.base64_encode( $row['image'] ).'"/>';
Your Java code is doing a Base64 encode of the image before sending it to the server. You do not need to encode it a second time when you go to display it. The result is a base64 encoded string of a base64 encoded string, which isn't what you want to do.
Try this instead:
echo '<img src="data:image/jpeg;base64,' . $row['image'] . '"/>';

Import data from a txt file in a MySQL database with PHP on visit

I'm using PHPMyAdmin to run my MySQL database.
Suppose we have this txt file "people.txt", a MySQL database and a PHP page in which are showed the data from the database. Suppose that data in the text file are stored with this syntax:
2015/16/01|Alex|Paris
2015/13/01|Johnny|Berlin
2015/11/01|Mary|Oslo
You can notice that each field is separated with a |
Is there any way to import these data using a PHP script? I want to show you a different script that, when the page is visited, send data to the database:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "my_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO `People` (data, name, city)
VALUES ('2015/10/01', 'Will', 'Rome')";
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id;
echo "OK!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
I want to emulate this script in order to let check, each time the page is visited, the txt file. Any help?
I tried to merge the PHP script that shows my data and the one that import them from the txt file but it doesn't seem to work properly..
<?php
$con=mysqli_connect("localhost","username","","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed: " . mysqli_connect_error();
}
$sql = "
LOAD DATA INFILE 'people.txt'
INTO TABLE `People`
FIELDS TERMINATED BY '|'
";
$result = mysqli_query($con,"SELECT * FROM `People`");
echo "<table class='people'>
<tr class='titles'>
<th>Data</th>
<th>Name</th>
<th>City</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Data'] . "</td>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['City'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Use the "LOAD DATA INFILE" statement to just load the data into the table every time the page is visited.
$sql = "
LOAD DATA INFILE 'people.txt'
INTO TABLE `People`
FIELDS TERMINATED BY '|'
";
One part of the SQL to look into are the REPLACE or IGNORE option, which determines what will happen if the script tries to insert a row that duplicate an existing unique key, if your table has any.
Also, if your input file has fields in a different order than your database table, then you can provide a list of columns at the end of the SQL, like (data, name, city).
Other than those things, I think you should simply be able to replace the $sql variable in your posted code with something like the above SQL, then run (as in your original code):
if ($conn->query($sql) === TRUE) {
echo "OK!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

mysqli_query not recognizing database?

I've already asked a question on this code I'm working on, just not about the same problem. Either way sorry for the repost!
So I'm having trouble with the code, as follows:
<?php
// Create connection
$host = "localhost";
$username="tudor";
$password="passw0rd";
$con=mysqli_connect($host, $username, $password);
if(! $con )
{
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully<br />';
$db_1 = mysqli_select_db( $con, 'db_1' );
if (! $db_1) {
die('Could not select database: ' . mysqli_error());
}
else {
echo "Database successfully selected<br />===============================<br />";
}
//===================================
$a = 1;
$b = 2234;
$table = "CREATE TABLE info (id INT NOT NULL AUTO_INCREMENT, city CHAR(40), country CHAR(40))";
if (! $table) {
die('Could not create table ' . mysqli_error($con));
}
else {
echo "Table created<br />";
}
$insert = "INSERT INTO info (city, country) VALUES ($a, $b)";
if (! $insert) {
die('Could not insert ' . mysqli_error($con));
}
else {
echo "Inserted<br />";
}
$select = "SELECT * FROM info";
$result = mysqli_query ($con, $insert);
if (! $result) {
die('Result not working ' . mysqli_error($con));
}
else {
echo "Result working<br />";
}
echo "result: ".$result['city']. " ";
mysqli_close($con);
?>
This outputs (blockquote doesn't display page breaks):
Connected successfully Database successfully selected
=============================== Table created Inserted Result not working Table 'db_1.info' doesn't exist
What does it mean by "Table 'db.info'" not existing? It clearly says that my info table was created...
What I tried doing is inverting the variables in the $result query: $result = mysqli_query ($insert, $con);, because I had seen that syntax in a book. However all it gave was the following message in the output:
Warning: mysqli_query() expects parameter 1 to be mysqli, string given
in C:\wamp...
Thoughts anyone? Thanks in advance!
Edit: really appreciate the help everyone, thanks a lot!
You are not doing a mysqli_query() on $table before your mysqli_query() on $insert, and you are not doing a mysqli_query() on $select
$table = "CREATE TABLE info (id INT NOT NULL AUTO_INCREMENT, city CHAR(40), country CHAR(40))";
if (! $table)
$insert = "INSERT INTO info (city, country) VALUES ($a, $b)";
if (! $insert) {
$select = "SELECT * FROM info";
$result = mysqli_query ($con, $insert);
if (! $result)
try adding the mysqli_query() -
$table_sql = "CREATE TABLE `info` (`id` INT NOT NULL AUTO_INCREMENT, `city` CHAR(40), `country` CHAR(40), PRIMARY KEY (`id`))";
$table = mysqli_query ($con, $table_sql);
if (! $table) {
die('Could not create table ' . mysqli_error($con));
}
else {
echo "Table created<br />";
}
$insert_sql = "INSERT INTO `info` (`city`, `country`) VALUES ('$a', '$b')";
$insert = mysqli_query ($con, $insert_sql);
if (! $insert) {
die('Could not insert ' . mysqli_error($con));
}
else {
echo "Inserted<br />";
}
$select = "SELECT * FROM `info`";
$result = mysqli_query ($con, $select);
if (! $result) {
die('Result not working ' . mysqli_error($con));
}
else {
echo "Result working<br />";
}
Edit
Also, this line will fail -
echo "result: ".$result['city']. " ";
as you have to fetch the array from the query using mysqli_fetch_array()
$results = mysqli_fetch_array($result);
echo "result: ".$results['city']. " ";
Table 'db_1.info' doesn't exist
Means, that table info does not exist in db db_1 so, make sure if that is the case.
ok. Here is your code.
if(! $con )
{
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully<br />';
if (!$con) {trigger_error("Could not connect to MySQL: " . mysqli_connect_error()); }
else { echo "Database successfully connected<br />===============================<br />"; }
$a = 1;
$b = 2234;
$table = mysqli_query($con,"CREATE TABLE IF NOT EXISTS info (`id` int(11) unsigned NOT NULL auto_increment,
`city` CHAR(40),
`country` CHAR(40), PRIMARY KEY (`id`) )ENGINE=MyISAM DEFAULT CHARSET=utf8");
if (!$table) {
die('Could not create table ' . mysqli_error($con));
}
else {
echo "Table created<br />";
}
$insert = mysqli_query ($con,"INSERT INTO info (city, country) VALUES ('$a', '$b')");
if (!$insert) {
die('Could not insert ' . mysqli_error($con));
}
else {
echo "Inserted<br />";
}
$select = mysqli_query ($con,"SELECT * FROM info");
$res=mysqli_fetch_array($select);
if (! $res) {
die('Result not working ' . mysqli_error($con));
}
else {
echo "Result working<br />";
}
echo "result: ".$res['city']. " ";
echo "result: ".$res['country']. " ";
mysqli_close($con);

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