Outputting values from MySQL into a preformatted table - php

I am making a periodic table and am new to php. I have looked far and wide for information on how to accomplish this task, but I can't find anything. What I want to do is query my database and get values for things like atomic weight, name, element symbol, etc, and have them populate in my periodic table that I have constructed with html and css. However, I just don't know to run the "while" loop and have the data populate in the appropriate spaces. I understand how to create a table with the results, but I don't understand how to have results populate into an html structure that has already been created. Here is a part of my code. Again, I am very new to php, so any help would be greatly appreciated. I'm fairly certain this has a lot to do with where I'm placing my opening/closing php tags. Essentially, how do I get the loop to recognize the variables within the html? Do I close php tags and reopen?
Thank you tremendously.
<?php
//query database (connection successful)//
$result=mysql_query("SELECT * FROM elementdata", $link);
//fetch results into array to loop through//
while($row = mysql_fetch_array($result)) {
//begin table structure where I would like to insert data//
<div id="hydrogen" class="element group1 period1">
<span class="number"> echo $row['atomicNumber']; </span><br>
<span class="symbol">H</span><br>
<span class="name"> echo $row['name']; </span><br>
<span class="molmass">1.007 94</span></div>
<div id="Helium" class="element group18 period1">
<span class="number">echo $row['atomicNumber'];</span><br>
<span class="symbol">He</span><br>
<span class="name"> echo $row['name']; </span><br>
<span class="molmass">4.002 602</span></div>
//...table continues...//
?>

You could go with two approaches, using PHP to echo the HTML or having PHP in the HTML.
PHP printing HTML
<?php
//query database (connection successful)//
$result=mysql_query("SELECT * FROM elementdata", $link);
//fetch results into array to loop through//
while($row = mysql_fetch_array($result)) {
//begin table structure where I would like to insert data//
echo '<div id="hydrogen" class="element group1 period1">';
echo ' <span class="number">' . $row['atomicNumber'] . '</span><br>';
echo ' <span class="symbol">H</span><br>';
echo ' <span class="name">' . $row['name'] . '</span><br>';
echo ' <span class="molmass">1.007 94</span></div>';
}
HTML with PHP
<?php
//query database (connection successful)//
$result=mysql_query("SELECT * FROM elementdata", $link);
//fetch results into array to loop through//
while($row = mysql_fetch_array($result)) {
?>
//begin table structure where I would like to insert data//
<div id="hydrogen" class="element group1 period1">';
<span class="number"><?php echo $row['atomicNumber']; ?></span><br>';
<span class="symbol">H</span><br>';
<span class="name"><?php echo $row['name']; ?></span><br>';
<span class="molmass">1.007 94</span></div>';
<?php
}

Well i am not sure about whether you are storing the molmass,symbol,group and period in the MySQL table, but you most probably are. Since i dont know what you named them, please replace molmass,atomicSymbol,atomic_group and atomic_period with your coloumn name.
You can use this code,
<?php
//query database (connection successful)//
$result=mysql_query("SELECT * FROM elementdata", $link);
//fetch results into array to loop through//
while($row = mysql_fetch_array($result)) {
// echo the first line, i.e the div
echo "<div id='{$row['name']}' class='element {$row['atomic_group']} {$row['atomic_period']}'>";
// Echo the atomic number, symbol, name and molmass
echo "<span class='number'>{$row['atomicNumber']}</span><br>";
echo "<span class='symbol'>{$row['atomicSymbol']}</span><br>";
echo "<span class='name'>{$row['name']}</span><br>";
echo "<span class='molmass'>{$row['molmass']}</span><br>";
echo "</div>";
}
?>
Explaination: The {} is required for us to insert the $row[''] syntax in a string, else it gives us trouble.
Rest we just loop over everything in the table, fetch what you named them and what group and period they belong to, create a div. Then we print each of their properties.

You need to step in and out of PHP
After :
//fetch results into array to loop through//
while($row = mysql_fetch_array($result)) {
If you want to output HTML, you must close PHP
?>
Now when you want to output some PHP variable inside a HTML tag :
<span class="number"><?php echo $row['atomicNumber']; ?></span><br>
Similar to the opening and closing tags in HTML, you enclose your PHP code within PHP tags.

Well, let's try one possible way:
<html>
<head>
</head>
<body>
<?php
open your db stuff
$query = " SELECT name,
symbol,
atomicnumber,
molmass,
otherstuff
FROM periodictabletable
WHERE index > 0 ";
$result = mysqli_query($cxn, $query) or die ("could not query database");
echo "<table>";
while ($row = mysqli_fetch_array($result))
{
echo "<tr><td>".$row['name']."</td><td>".$row['symbol']."</td><td>".$row['atomicnumber']."</td><td>".$row['molmass']."</td></tr>";
}
echo "</table>";
?>
</body>
</html>
Once you get this up and running, you can embed all kinds of formatting tags into the html, just make sure you only use single quotes for stuff like - class='numbercolor' .
But there are many ways to do this. You could make the table in html, then populate it with an ajax call - depends on what you want to do.
Have fun!

Related

PHP dropdown menu that concatenates 2 rows from MySQL data table

Not experienced with creating forms in PHP.
I can get my form to produce a dropdown list that has one of my rows listed as an option, but as soon as I try to concatenate 2 rows together (from the same table) for option output...
a) It just doesn't work and I get errors
b) I get the first row as a single option, then my next row as a separate option.
I know there is a simple solution to this, but I am an online student just learning, and I can't seem to find a good example of the code to write it. I'm pretty sure it's an issue of quotes not being placed correctly.
MySQLTable Data:
Table Name: courses
Table Rows: course_id, course_name, max_enrolment
Sample Data: LO-COMP-8001, Intro to HTML, 20
function select_course(){
global $open;
$select = "SELECT * FROM courses";
$result = mysqli_query($open, $select);
return $result;
}
<form action="insert.php" method="post">
<dl>
<dt>Select Course</dt>
<dd><select name="course_id">
<?php // CREATE dropdown menu
$result = select_course();
while ($row = mysqli_fetch_assoc($result)) {
foreach ($row as $selection) {
echo "<option value=\"$selection\">$selection</option>";
}}
?>
</select>
</dd>
</dl>
Then there are a few more form fields such as student name and student id afterwards...
Goal Output:
course_id course-name
"LO-COMP-8001 Intro to HTML" ... as a single connected dropdown option and other remaining courses in a dropdown menu
Current Output:
LO-COMP-8001 (as an option)
Intro to HTML (as another option! ... No good)
20 (must be hidden, I need to check if course is full in another function and either allow or deny a student to enrolled etc.)
I have tried:
// output is the one mentioned above..
echo "<option value=\"$selection\">$selection</option>";
// or alternatively...
echo '<option value="'.$row['course_id'].'">'.$row['course_id'].'</option>';
But the second option creates all kinds of weird results.
This is what I am experimenting with right now...
echo '<option value="'.$row['course_id'] $row['course_name']'">'.$row['course_id'] $row['course_name'].'</option>';
But there is a bunch of issues with quotes and square brackets, and I just don't know how to format it correctly for the output.
Any assistance is appreciated.
$row holds the entire row as an associative array therefore no need for the 'foreach' loop.
function select_course(){
global $open;
$select = "SELECT * FROM courses";
$result = mysqli_query($open, $select);
return $result;
}
<form action="insert.php" method="post">
<dl>
<dt>Select Course</dt>
<dd><select name="course_id">
<?php // CREATE dropdown menu
$result = select_course();
while ($row = mysqli_fetch_assoc($result)) {?>
<option value="<?php echo $row["course_id"]; ?>"><?php echo $row["course_name"]; ?></option>
<?php }
?>
</select>
</dd>
</dl>
</form>
I was able to come up with another solution as well:
Once the foreach loop was removed, I tried cleaning up the code some... I'm not sure if this is uncommon or 'bad' style, but it does work.
$result = select_course();
while ($row = mysqli_fetch_assoc($result)) {
$course_id = $row['course_id'];
$course_name = $row['course_name'];
echo "<option value=\"$course_id\">$course_id $course_name</option>";
Results in: LO-COMP-8001 Intro to HTML as a single option, plus all my other courses in the database.

Export MySQL table to CSV via PHP by checkbox selection

I need to display a list of results form a survey on a PHP page then export them to a CSV file. The list also acts as a summary that can be clicked thorugh to the full result.
I have all that sorted but now I need to have the CSV export by a check bx selection so that we dont need to download the entire databse each time just the ones we need.
My code so far below.
<div class="resultsList">
<h1>PEEM Results List</h1>
<a class="exportCSV" href="https://domain.com/downloadcsv.php">Export to CSV</a>
<!-- Export CSV button -->
<h3 class="resultsbydate">All results by date</h3>
<div class="resultsListHeader">
<div class="clientidTab">Agency</div>
<div class="clientidTab">Family ID</div>
<div class="clientidName">Name</div>
<div class="clientidTab">Date</div>
<div class="clientidTab"></div>
</div>
<div class="entriesListMain">
<?php
$connection = mysql_connect("localhost", "username", "password"); // Establishing Connection with Server
$db = mysql_select_db("database_name", $connection); // Selecting Database
//MySQL Query to read data
$query = mysql_query("select * from results ORDER BY peemdate DESC", $connection);
while ($row = mysql_fetch_array($query)) {
echo "<div><input type=\"checkbox\" name=\"xport\" value=\"export\"><span>{$row['client_id']}</span> <span>{$row['family_id']}</span> <span>{$row['firstname']} {$row['lastname']}</span> <span>".date("d F Y", strtotime($row['peemdate']))."</span>";
echo "<span><a class=\"parents-button\" href=\"peem-parent-repsonses.php?id={$row['survey_id']}\"><strong>Parent’s Review</strong></a></span>";
echo "<span><strong>View Results</strong></span>";
echo "</div>";
}
?>
</div>
</div>
<?php
if (isset($_GET['id'])) {
$id = $_GET['id'];
$query1 = mysql_query("select * from results where survey_id=$id", $connection);
while ($row1 = mysql_fetch_array($query1)) {
?>
<?php
}
}
?>
<?php
mysql_close($connection); // Closing Connection with Server
?>
And the downloadcsv.php
<?php
$conn = mysql_connect("localhost","username","password");
mysql_select_db("databasename",$conn);
$filename = "peem_results.csv";
$fp = fopen('php://output', 'w');
$query = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='realwell_peemfinal' AND TABLE_NAME='results'";
$result = mysql_query($query);
while ($row = mysql_fetch_row($result)) {
$header[] = $row[0];
}
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
fputcsv($fp, $header);
$query = "SELECT * FROM results";
$result = mysql_query($query);
while($row = mysql_fetch_row($result)) {
fputcsv($fp, $row);
}
exit;
?>
Any help with this would be great, cheers
Updated with a screenshot of what I am trying to achieve
The initial result set needs to be wrapped in a form which POST to the next page.
The Checkbox must send an array of ids to the export script.
<input type='checkbox' name='xport[]' value='ID_OF_THE_ROW_HERE'>
The [ ] after xport means that $_POST['xport'] will be an array of values.
The export page can collapse that array of ids into a comma separated string and to be used the query:
SELECT * FROM results WHERE id IN (4,7,11,30)
<form method="POST" action="downloadcsv.php">
<h1>PEEM Results List</h1>
<a class="exportCSV" href="https://domain.com/downloadcsv.php">Export to CSV</a>
<!-- Export CSV button -->
<h3 class="resultsbydate">All results by date</h3>
<div class="resultsListHeader">
<div class="clientidTab">Agency</div>
<div class="clientidTab">Family ID</div>
<div class="clientidName">Name</div>
<div class="clientidTab">Date</div>
<div class="clientidTab"></div>
</div>
<div class="entriesListMain">
<?php
$connection = mysql_connect("localhost", "username", "password"); // Establishing Connection with Server
$db = mysql_select_db("database_name", $connection); // Selecting Database
//MySQL Query to read data
$query = mysql_query("select * from results ORDER BY peemdate DESC", $connection);
while ($row = mysql_fetch_array($query)) {
echo "<div><input type='checkbox' name='xport[]' value='{$row['client_id']}'><span>{$row['client_id']}</span> <span>{$row['family_id']}</span> <span>{$row['firstname']} {$row['lastname']}</span> <span>".date("d F Y", strtotime($row['peemdate']))."</span>";
echo "<span><a class=\"parents-button\" href=\"peem-parent-repsonses.php?id={$row['survey_id']}\"><strong>Parent’s Review</strong></a></span>";
echo "<span><strong>View Results</strong></span>";
echo "</div>";
}
?>
</div>
</form>
Change $row['client_id'] to the correct value
Then in the export script:
<?php
/*
Expecting $_POST['xport'] array of row ids
*/
if( !isset($_POST['xport']) OR !is_array($_POST['xport']) ) {
exit('No rows selected for export');
}
$conn = mysql_connect("localhost","username","password");
mysql_select_db("databasename",$conn);
$filename = "peem_results.csv";
$fp = fopen('php://output', 'w');
$query = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='realwell_peemfinal' AND TABLE_NAME='results'";
$result = mysql_query($query);
while ($row = mysql_fetch_row($result)) {
$header[] = $row[0];
}
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
fputcsv($fp, $header);
//Cast all ids to integer
$ids = $_POST['xport'];
array_walk($ids, function(&$value, $key) {
$value = (int)$value;
});
$ids = implode(', ', $ids);
$query = "SELECT * FROM results WHERE id IN ($ids)";
$result = mysql_query($query);
while($row = mysql_fetch_row($result)) {
fputcsv($fp, $row);
}
exit;
?>
So if I'm getting this correctly, you just need to be able to check checkboxes to select the databses ($rows) you want to insert into the csv file....
Every checkbox that you checked will be in the $_POST variable, so:
1st you make an array with all the names of checkbox options (databases), for example
$all_db = ['database1', 'database2', 'database3'];
2nd you loop through each of the values in $all_db and check if they exist in the $_POST array, if they do, then you can export the row
foreach( $all_db as $db_check ) {
if ( array_key_exists( $db_check, $_POST ) {
// EXPORT TO CSV
}
}
Don't forget ! This means the "name" attribute of the checkbox should be the name of the database.
If you don't want to have a static list of databases (i.e. there is a possibillity of them having different names in the future / there will be moreor maybe less etc then let me know i can edit my answer if needed :) )
( If you use the $_GET variable, then you can do the same thing just change $_POST to $_GET)
Know though that $_GET comes over as a bit amateuristic for the enduser if he gets a thousand variables in his URL,
$_POST is often a better alternative since it is hidden and cleaner for the enduser...
EDIT: UPDATING ANSWER (SEE COMMENT)
So basically you need people to be able to choose what rows they export from you dB...
First of all this means we need a unique ID for each row,
This can either be a column used solely for that (i.e. ID column with auto increment and unique attribute)
Or this can be a column you already have, just make sure it's a unique column so we don't get dupliate values (you'll see why below)
Then we give the value of this unique ID column to the checkbox's "name" attribute, and using jquery / php we append / prepend a static string...
For example, using your family ID:
"rownumber_" + $family_ID
This gets us (again using your example) :
$_POST[] = ['rownumber_123456' => 1, 'rownumber_0000000' => 1, .....]
So then in your PHP file you just do the following to add the correct lines to your CSV:
while($row = mysql_fetch_row($result)) {
if ( array_key_exists($row['your_row_id'], $_POST) {
fputcsv($fp, $row);
}
}
-- Again using your example with family_ID : --
while($row = mysql_fetch_row($result)) {
if ( array_key_exists($row['family_ID'], $_POST) {
fputcsv($fp, $row);
}
}
EDIT: Updating answer for comment no.2
So little sidenote if you are going to loop through html using php
(i.e. loop trhough db rows and print them out in an orderly fashion)
Then you propably want to use the ":" variants of the loops,
While() :
for() :
foreach() :
if () :
.....
These variants allow yu to close the php tag after the ":" and whataver html / css / php / jquery you put in the condition / loop will be executed like normal...
For example you can do :
<ul>
<?php foreach ($row as $columnkey => $columnvalue): ?>
<img src="whateveryouwant"?>
<li class="<?php echo $columnkey;?>">This is my value: <?php echo $columnvalue; ?></li>
<?php endforeach; ?>
</ul>
When you do it this way it's much cleaner and you won't have any problems using double quatation signs and all that stuff :)
So using that method here is how your displayed list would look like in code:
<div class="entriesListMain">
<?php
$connection = mysql_connect("localhost", "username", "password"); // Establishing Connection with Server
$db = mysql_select_db("database_name", $connection); // Selecting Database
//MySQL Query to read data
$query = mysql_query("select * from results ORDER BY peemdate DESC", $connection);
while ($row = mysql_fetch_array($query)) :
?>
<div>
<input type="checkbox" name="<?php echo $row['family_id']; ?>" value="export">
<span><?php echo $row['client_id']; ?></span>
<span><?php echo $row['family_id']; ?></span>
<span><?php echo $row['firstname'] . " " . $row['lastname']; ?></span>
<span><?php echo date("d F Y",strtotime($row['peemdate']); ?></span>;
<span>
<a class="parents-button" href="peem-parent-repsonses.php?id=<?php echo $row['survey_id']; ?>">
<strong>Parent’s Review</strong>
</a>
</span>
<span>
<a href="peem-repsonses.php?id=<?php echo $row['survey_id']; ?>">
<strong>View Results</strong>
</a>
</span>
</div>
<?php endwhile; ?>
</div>
Like this the checkbox will get the name of the family ID, and so in your csv.php you can use this code :
while($row = mysql_fetch_row($result)) {
if ( array_key_exists($row['family_ID'], $_POST) {
fputcsv($fp, $row);
}
}
Since now it will check for each row wether the family ID of the SQL row is posted as a wanted row in the $_POST variable (checkbooxes) and if not it won't export the row into the csv file ! :)
So there you go ^^
EDIT 3: Troubleshooting
So there are a couple of things that you do in this function,
the form,
Do the checkboxes in your html form have the family_ID in their name attribute ?
(i.e. <input type="checkbox" name="<?php echo $row['family_id']; ?>".... check if the name attribute is really filled )
you post stuff from a form, (your checkboxes and stuff)so let's see what actually gets posted,
die(print_r($_POST)); - This means you want php to die after this line (stop working at all), then print out a variable as is (sort of xml format you'll see)
So then you will get a whole bunch of information, if you want to see this information in a nicely formated way, just right click inspect element on it :)
Then see how your checkboxes are coming out of the $_POST variable,
(they should have the family_ID as a key and a value of 1)
If that's all ok, then check your row['family_ID'] variable see if the family_ID is filled correctly, do the same with your whole $row variable, in fact check every variable you use in csv.php and then check why the key does not exist in the array you are searching for :)
Also dont forget to check that you filled the array_key_exists( has a key FIRST and an array[] LAST )
I can't help you directly with this , since this will propably be a faulty variable or a mistake in your form so try to find this yourself, if still nothing , post these variables values:
$_POST
$row
and the full HTML of your form

reading entries from database through a drop down list

how can i set it that the section drop down list shows all sections available for a certain subject, depending on the previous drop down list that contains subjects. For example: if i chose the subject A , it should show me all sections of subject A available. Currently the drop down of the subject works, it fetches all subjects available but im unable to make the second drop down fetch the sections since i want to make such that:
select section from class WHERE (name of subject chosen above is equal to the name column in the database.
Please ignore my code style since im a beginner after all. Thank you in advance.
My code:
<div>
<label for="subjects" accesskey="o">Subject</label>
<?php
$conn = new mysqli('localhost', 'afhfhdfhf', 'fhfhhfhfhfhf', 'fhfhfhfh')
or die ('Cannot connect to db');
$result = $conn->query("select name from class");
echo "<html>";
echo "<body>";
echo "<select name='subject'>";
while ($row = $result->fetch_assoc()) {
unset($id, $name);
$name = $row['name'];
echo '<option value="subject">'.$name.'</option>';
}
echo "</select>";
echo "</body>";
echo "</html>";
?>
</div>
<br>
<div>
<label for="section" accesskey="o">Section</label>
<?php
$conn = new mysqli('localhost', 'fgfgfgfg', 'rfgfgfgfg!~fgfgf', 'fgfgfgf')
or die ('Cannot connect to db');
$result = $conn->query("select section from class WHERE name = '$name'");
echo "<html>";
echo "<body>";
echo "<select name='id'>";
while ($row = $result->fetch_assoc()) {
unset($id, $name);
$name = $row['name'];
echo '<option value="">'.$name.'</option>';
}
echo "</select>";
echo "</body>";
echo "</html>";
?>
</div>
<br>
(n.b. this really should have been a comment, but it was too long for that, so answer it is :-)
You've got a few problems there... first, you are echoing out <html> and <body> tags, you already have those on the page, so you don't need to do that.
The second problem is that $name doesn't really exist in the way you are looking in the second query. In fact, it'll be the value of the last name you echo'd out in the first loop.
So, the fundamental issue is that PHP runs on the server and then is passed to the client and you want to limit a select based on user input that happens in the browser. So what you need to do is either on selection of the subject, submit back to the server to get the section OR you could use something like jQuery to do an AJAX call back to the server to retrieve this info (either as JSON that you can parse and use, or as HTML that you can plop into the form). 2nd option is definitely the way to go.
Have a google about this kinda thing and you'll find LOADS of examples and come on back here if you hit a road block :-)

PHP, display mysql row in view

I'm having trouble displaying the sql below in the hph view file.
$query = mysqli_query($con, "SELECT TF.tf_ID AS QuestID, TF.Question AS Question FROM QuizQuestions quest, addTF TF WHERE quest.QuestID = TF.tf_ID AND quest.QuizID ='".$quizID."' AND quest.Type = 'tf'");
$rows = array();
while ($row = mysqli_fetch_assoc($query)) {
$rows[] = $row;
}
echo json_encode($rows);
This is the part of the php view that is supposed to display the sql. I know it is wrong but I don't know how to fix it. Any help is welcome.
<?php foreach($json as $tf) :?> <?php echo $tf['Question']; ?> <div class="row-fluid"><div class="span8">
<div class="btn view" id="view" style="width: 98%">
<p class="text-left" style="margin: 0;float: left;">
<input type ="hidden" value="tf" name="type">
<input type="checkbox" id="questID" value="<?php echo $tf['tf_ID'];?>" name="questID" class="questID" > <?php echo 'Question: '.$tf['Question']; ?> </input><br/>
<input type="hidden"> <?php echo 'Answer: '.$tf['Answer'] ; ?> </input><br/>
</div> </div> </div> <?php endforeach; ?>
I've used similar codes and they work. They problem is I do not know how to work with sql "AS". My apology in advance if this question was once asked and for the format.
There is no method called mysqli_fetch_assoc(). There is mysql_fetch_assoc() but not mysqli_fetch_assoc().
You can do this to get the rows:
$query = "SELECT TF.tf_ID AS QuestID, TF.Question AS Question FROM QuizQuestions quest, addTF TF WHERE quest.QuestID = TF.tf_ID AND quest.QuizID ='".$quizID."' AND quest.Type = 'tf'";
$result = mysqli_query($con, $query);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
If you are calling the query through an Ajax method and returning the data to JavaScript you should JSON encode. However, if you are just printing the rows with PHP there is no reason to JSON encode them.
To iterate the rows in PHP you can do:
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo '<div>' . $row['foo']; . '</div><div>' . $row['bar']; . '</div>';
}
I'm not clear what you are trying to do.
The top code create some JSON which will be sent to the browser. Presumably in response to a AJAX or jQuery request. Once the JSON is on the browser it can be added to the current page using Java-Script.
The second code fragment is PHP which always executes on the server, but your data is on the client???
I would have expected something more like...
$rows = mysqli_fetch_assoc($query)
echo "<div>\n";
foreach($rows as $row) {
// generate one row getting values as {$row['fieldname']}
}
echo "</div>";
Also - if you don't generate 100% valid and error free html you not only have to test on all current browsers, you cannot complain if a new browser displays it wrongly next release.

Is it possible to Query a Mysql database from a field selected from dropdown menu populated from a Query in php

Hello i am new to php and i have tried to find a piece of code that i can use to complete the task i need, i currently have a page with a form set out to view the criteria of a course. also i have a dropdown menu which currently holds all the course codes for the modules i have stored in a database. my problem is when i select a course code i wish to populate the fields in my form to show all the information about the course selected. The code i am trying to get to work is as follows:
<?php
session_start();
?>
<? include ("dbcon.php") ?>
<?php
if(!isset($_GET['coursecode'])){
$Var ='%';
}
else
{
if($_GET['coursecode'] == "ALL"){
$Var = '%';
} else {
$Var = $_GET['coursecode'];
}
}
echo "<form action=\"newq4.php\" method=\"GET\">
<table border=0 cellpadding=5 align=left><tr><td><b>Coursecode</b><br>";
$res=mysql_query("SELECT * FROM module GROUP BY mId");
if(mysql_num_rows($res)==0){
echo "there is no data in table..";
} else
{
echo "<select name=\"coursecode\" id=\"coursecode\"><option value=\"ALL\"> ALL </option>";
for($i=0;$i<mysql_num_rows($res);$i++)
{
$row=mysql_fetch_assoc($res);
echo"<option value=$row[coursecode]";
if($Var==$row[coursecode])
echo " selected";
echo ">$row[coursecode]</option>";
}
echo "</select>";
}
echo "</td><td align=\"left\"><input type=\"submit\" value=\"SELECT\" />
</td></tr></table></form><br>";
$query = "SELECT * FROM module WHERE coursecode LIKE '$Var' ";
$result = mysql_query($query) or die("Error: " . mysql_error());
if(mysql_num_rows($result) == 0){
echo("No modules match your currently selected coursecode. Please try another coursecode!");
} ELSE {
Coursecode: echo $row['coursecode'];
Module: echo $row['mName'];
echo $row['mCredits'];
echo $row['TotalContactHours'];
echo $row['mdescription'];
echo $row['Syllabus'];
}
?>
however i can only seem to get the last entry from my database any help to fix this problem or a better way of coding this so it works would be grateful
Thanks
The main error is in your final query, you're not actually fetching anything from the query, so you're just displaying the LAST row you fetched in the first query.
Some tips:
1) Don't use a for() loop to fetch results from a query result. While loops are far more concise:
$result = mysql_query(...) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
...
}
2) Add another one of these while loops to your final query, since it's just being executed, but not fetched.
For me i would use some javascript(NOTE: i prefer jQuery)
An easy technique would be to do this(going on the assumption that when creating the drop downs, your record also contains the description):
Apart from creating your dropdown options like this <option value="...">data</option>, you could add some additional attributes like so:
echo '<option value="'.$row['coursecode'].'" data-desc="'.$row['description'].'">.....</option>
Now you have all your drop down options, next is the javascript part
Let's assume you have included jQuery onto your page; and let's also assume that the description of any selected course is to be displayed in a <div> called description like so:
<div id="course-description"> </div>
<!--style it how you wish -->
With your javascript you could then do this:
$(function(){
$("#id-of-course-drop-down").change(function(){
var desc = $(this).children("option").filter("selected").attr("data-des");
//now you have your description text
$("#course-description").html(desc);
//display the description of the course
}
});
Hope this helps you, even a little
Have fun!
NOTE: At least this is more optimal than having to use AJAX to fecch the description on selection of the option :)

Categories